为什么我在 CodeChef Closest Divisor 程序中出错?

问题描述

我正在努力解决 Codechef Closest Divisor Problem

我不明白为什么它给了我错误的解决方案。

问题陈述是

给定两个整数A和B,找出能被B完全整除的最大数≤A。

输入: 输入由两行组成。 输入的第一行包含一个整数 A。 输入的第二行包含一个整数 B。

输出: 将能被 B 整除的最大整数 ≤A 列在单独的行中。

约束 1≤B≤A≤10^9

这是我的代码

#include<bits/stdc++.h>
#define ll long long
using namespace std;

void file_i_o() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  #ifndef ONLINE_JUDGE
    freopen("Input.txt","r",stdin);
    freopen("Output.txt","w",stdout);
  #endif
}

int main(int argc,char** argv) {   
  file_i_o();
  //write your code here
  ll A,B;
  cin>>A>>B;
  ll q = A/B;
  ll n1 = B*q;
  ll n2 = 0;
  if(A*B > 0) {
    n2 = B*(q+1);
  } else {
    n2 = B*(q-1);
  }
  if(abs(A-n1) < abs(A-n2)) {
    if(n1<=A) {
      cout<<n1;
    } 
  } else {
    if(n2<=A) {
      cout<<n2;
    }
  }
  return 0;
}

解决方法

我认为你把问题复杂化了。我只是看着问题。不需要那么复杂。

这是我的解决方案(AC):

void solve(){
    int a,b;
    read(a,b);
    cout << a / b * b << endl;
}

如果你非要找出问题所在,我只能说A * B > 0永远是真的,没必要去判断,也许就是问题所在。

,

我不明白你为什么要写这么多代码来解决可以用两行代码完成的事情。

解决办法

#include<bits/stdc++.h>
#define ll long long int
using namespace std;

void file_i_o() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  #ifndef ONLINE_JUDGE
    freopen("Input.txt","r",stdin);
    freopen("Output.txt","w",stdout);
  #endif
}

int main(int argc,char** argv) {   
  file_i_o();
  ll A,B;
  cin>>A>>B;
  ll ans = B*(A/B);
  cout << ans;
  return 0;
}

我已经在 codechef 上运行了这段代码并且可以正常工作。

看到这个solution

编辑 - 如果您对我的回答感到满意,请标记。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...