How to check for division by 7 for big number in C++?

前端 未结 9 687
傲寒
傲寒 2020-12-17 01:57

I have to check, if given number is divisible by 7, which is usualy done just by doing something like n % 7 == 0, but the problem is, that given number can have

9条回答
  •  轮回少年
    2020-12-17 02:50

    You can compute the value of the number modulo 7.

    That is, for each digit d and value n so far compute n = (10 * n + d) % 7.

    This has the advantage of working independently of the divisor 7 or the base 10.

    I solved this problem exactly the same way on one of programming contests. Here is the fragment of code you need:

    int sum = 0;
    while (true) {
      char ch;
      cin>>ch;
      if (ch<'0' || ch>'9') break; // Reached the end of stdin
      sum = sum*10; // The previous sum we had must be multiplied
      sum += (int) ch;
      sum -= (int) '0'; // Remove the code to get the value of the digit
      sum %= 7; 
    }
    
    if (sum==0) cout<<"1";
    else cout<<"0";
    

    This code is working thanks to simple rules of modular arithmetics. It also works not just for 7, but for any divisor actually.

提交回复
热议问题