
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Fermat's Last Theorem in C++
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 −
an + bn = cn
i.e. if n <= 2, an + bn = cn
Otherwise, an + bn != 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.
Program to illustrate the working of our solution,
Example
#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!
- Related Articles
- Midy’s theorem in C++
- Lagrange’s four square theorem in C++
- Bayes Theorem for Conditional Probability in C/C++
- Extended Midy's theorem in C++
- Fermat's little theorem in C++
- An application on Bertrandís ballot theorem in C/C++
- C++ Program to Implement Euler Theorem
- C++ Program to Implement the Vizing’s Theorem
- C++ Program to Implement Fermat’s Little Theorem
- C++ Program for Zeckendorf's Theorem?
- Last Stone Weight II in C++
- Length of Last Word in C++
- Carnots Theorem
- Last Substring in Lexicographical Order in C++
- Explain Arden’s Theorem in TOC.
