# Fermat's Last Theorem in C++

C++Server Side ProgrammingProgramming

Fermat’s last theorem in number theory also known as Fermet’s conjecture is a theorem that states that for power n greater than 2. No three values a, b, c satisfy −

a+ b= cn

i.e.     if n <= 2,               an + b= cn

Otherwise,   an + b!= cn

Example of values for n = 2,

3, 4, 5 => 32 + 42 = 9 + 16 = 25 = 52

5, 12, 13 => 25 + 49 = 169 = 132.

In this problem, we are given three values, L, R, pow denoting range [L, R] and power. Our task is to verify the fermat’s last theorem for the given range and power.

Let’s take an example to understand the problem,

Example 1:

Input: L = 4, R = 12, power = 2

Output: 5, 12, 13

Example 2:

Input: L = 4, R = 12, power = 4

Output: No such value found

Solution Approach:

Here, we will check if the power is greater than 2 or not. If it's greater, print No such value found.

Else check in the limit if there is a value satisfying the condition an + bn = cn.

## Example

Live Demo

#include <iostream>
#include <math.h>
using namespace std;

void checkFermatsLastTh(int L, int R, int n) {

if (n >= 3)
cout<<"No example found!";
else {
for (int a = L; a <= R; a++)
for (int b=a; b<=R; b++)
{
int sum = pow(a, n) + pow(b, n);
double c = pow(sum, 1.0/n);
int cpowN = pow((int)c, n);
if (cpowN == sum)
{
cout<<"Example found with value : "<<a<<", "<<b<<", "<<c;
return;
}
}

cout << "No example found!";
}
}

int main() {

int L = 3, R = 15, power = 2;
cout<<"Run 1 \n";
checkFermatsLastTh(L, R, power);

L = 5, R = 42; power = 5;
cout<<"\n\nRun 2\n";
checkFermatsLastTh(L, R, power);

return 0;
}

## Output −

Run 1
Example found with value : 3, 4, 5
Run 2
No example found!
Published on 22-Jan-2021 13:32:48