samedi 31 août 2019

Unexpected function behavior

I have the following function. It just multiplies some powers of primes:

int solve(int n){
    long long solution = 1;

    for (int i=2; i<=n; i++){
        if (primes[i]){
            //std::cout << "p" << i << " : " << std::pow(i, find_last_power(n, i)) << std::endl;
            solution *= std::pow(i, find_last_power(n, i));
        }
    }
    return solution;
}

  • primes is an array of n+1 booleans whose value primes[i] is true if i is prime and false if i is composite.
  • find_last_power(n, p) returns the exponent (int) of the largest power of p that is less than or equal to n.

If you uncomment the debug line and run solve(20) it writes out:

p2 : 16
p3 : 9
p5 : 5
p7 : 7
p11 : 11
p13 : 13
p17 : 17
p19 : 19
232792237 // this is the return value of solve(20)
          // it is supposed to be the product of the numbers on the right (16,9...)

But the returned number is a product of all numbers except 19. I find this bizzare since the debug line clearly shows that the program went over the multiplication line. Moreover, after running the program in a debugger (GDB) the program executes correctly.

If anyone wants the full code it's here. It's only about 40 lines. Any help is appreciated.

Aucun commentaire:

Enregistrer un commentaire