Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fermat's Last Theorem algorithm

Tags:

c++

algorithm

I'm taking this definition of Fermat's Last Theorem.

I tried to code an algorithm to validate it for small values:

#include <iostream>
#include <cmath>
using namespace std;

int main() 
{
    //a^n + b^n = c^n

    int a, b, c, n, count = 0;

    for (n = 3; n < 1000; n++)
        for (a = 1; a < 1000; a++)
            for (b = 1; b < 100; b++)
                for (c = 1; c < 1000; c++)
                {
                    if (a != b && b != c && a != c)
                    {
                        if (pow(a,n) + pow(b,n) == pow(c,n))
                        {
                            cout << "\na: " << a << " b: " << b << " c: " << c << " n: " << n;
                            count++;
                        }
                    }
                }

    cout << count << " combinazioni";

}

And this is a screen of a piece of output: Image

How is it be possible? Am I missing something about "great integers" in C++ programming that can get a wrong result?

like image 887
Francesco Bonizzi Avatar asked Jun 12 '13 12:06

Francesco Bonizzi


1 Answers

Your pow() functions are overflowing; remember an int has a limited size.

For example, pow(256, 4) will overflow on 32 bit, pow(256, 8) on 64 bit, even if you use unsigned data types.

Technically int overflow is undefined behaviour so, anything could happen, including wrap around (i.e. back to 0), or nasal demons.

unsigned int computations are modulo 2 raised to the power of WIDTH as per the standard; i.e. will always wrap around.

like image 101
Bathsheba Avatar answered Oct 08 '22 16:10

Bathsheba