Exercise 4.5. Fermat\'s Last Theorem says that there are no integers a, b, and c
ID: 663134 • Letter: E
Question
Exercise 4.5. Fermat's Last Theorem says that there are no integers a, b, and c such that except in the case when n 2. Write a method named checkFermat that takes four integers as parameters a, b, c and n and that checks to see if Fermat's theorem holds. If n is greater than 2 and it turns out to be true that a" +b" c", the program should print Chapter 4. Conditionals and recursion "lloly sumokes, Fermat was wrong!" Otherwise the program should print "No, that doesn't work." You should assume that there is a method named raiseToPow that takes two integers as arguments and that raises the first argument to the power of the second. For example: int x raise ToPow(2, 3) would assigu the value 8 to x, because 2 8.Explanation / Answer
// FermatLastMethod.java
package Fermat;
import java.util.Scanner;
/**
*
* @author anurag
*/
public class FermatLastTheorem {
// Method to raiseToPow(int, int)
public static int raiseToPow(int a,int n)
{
int x=1;
while(n>0)
{
x=x*a;
n--;
}
return(x);
}
// Method to checkFermat(int, int, int, int)
public static int checkFermat(int a,int b,int c,int n)
{
if((raiseToPow(a, n)+raiseToPow(b, n))==raiseToPow(c, n))
{
return 1;
}
else
return 0;
}
public static void main(String[] args) {
// Taking Input from user
Scanner sc=new Scanner(System.in);
System.out.println("enter the values of a, b, c, n :");
int a=sc.nextInt();
int b=sc.nextInt();
int c=sc.nextInt();
int n=sc.nextInt();
// Checking for Fermat's Last Method and Printing Output
if(n==2)
{
System.out.println("for n=2, Fermat's Always Work");
}
else if(checkFermat(a, b, c, n)==1)
{
System.out.println("Holy smokes, Fermat was wrong!");
}
else
{
System.out.println("No, that doesn't work");
}
}
}
Some Sample Outputs are:
Output 1:
enter the values of a, b, c, n :
2 3 4 5
No, that doesn't work
Output 2:
enter the values of a, b, c, n :
2 3 4 0
No, that doesn't work
Output 3:
enter the values of a, b, c, n :
2 5 8 1
No, that doesn't work
Output 4:
enter the values of a, b, c, n :
34 56 100 8
No, that doesn't work
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.