首页 > 解决方案 > 为什么我在 CodeChef Closest Divisor 程序中出现错误?

问题描述

我正在尝试解决 Codechef 最近除数问题

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

问题陈述是

给定两个整数 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;
}

标签: c++numbersc++14theorynumber-theory

解决方案


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

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

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

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


推荐阅读