0

Now i want to check that if value

int a = pow(9.0,100);
int b = 81;
int c = 547;

when i use a - b, the value should be can divide by c without remainder;

if( (a-b) % 547 == 0 )
     cout << "Correct" << endl;
else
     cout << "Wrong" << endl;

but the output always go wrong and i see website links. the answer should be correct. Link can be reference to thread here : How to calculate modulus of large numbers?

but mine one when do the congruence modulo it's involve minus sign. so dont know how to write the algorithm

Community
  • 1
  • 1
user3664490
  • 217
  • 4
  • 13

2 Answers2

2

9^100 is about 10^95, so it overflow int. Instead of calculating 10^95 and then modulo you can calucate it with normal int with something like this:

int c=1;
for(int i=0; i<100; ++i) 
    c = (c * 9) % 547;

so c value is always below 547. You can also speed it up by using binary power method.

For your second question - easiest method to compute mod value for negative value is to do this with this code:

int mod(int a, int n) {
    int res = a % n;
    if (res < 0) res = res + n;
    return res;
}
Lukasz
  • 186
  • 3
1

9^100 is likley of out range for int. So you should calculate powermod(9,100,N) where N can be int or use class that can store arbitrary size integer

Luka Rahne
  • 10,336
  • 3
  • 34
  • 56
  • 1
    The point is that you can reduce intermediate results so that you never get numerical overflow. One has `(a*b) mod N == ((a mod N)*(b mod N)) mod N` so that there are never numbers larger than N² during the computation of powermod. – Lutz Lehmann May 29 '14 at 11:47