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

前端 未结 9 655
傲寒
傲寒 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:46

    you can use a known rule about division by 7 that says: group each 3 digits together starting from the right and start subtracting and adding them alternativly, the divisibility of the result by 7 is the same as the original number:

    ex.:

    testing 341234612736481253489125349812643761283458123548213541273468213
            549821354182354891623458917245921834593218645921580
    
       (580-921+645-218+593-834+921-245+917-458+623-891+354-182
        +354-821+549-213+468-273+541-213+548-123+458-283+761-643
        +812-349+125-489+253-481+736-612+234-341 
        = 1882 )
        % 7 != 0 --> NOK!
    

    there are other alternatives to this rule, all easy to implement.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-17 02:52

    At first Take That Big Number in string And then sum every digit of string. at last check if(sum%7==0)

    Code:

    #include <bits/stdc++.h>
    using namespace std;
    int main()
    {
        long long int n,i,j,sum,k;
        sum=0;
        string s;
        cin>>s;
        for(i=0;i<s.length();i++)
        {
            sum=sum+(s[i]-'0');
        }
    
        if(sum%7==0)
        {
            printf("Yes\n");
        }
        else
        {
            printf("No\n");
        }
    
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题