Problem:
An algorithm due to Fermat can be used to find the largest factor f (less than or equal to squareroot(n)) of an odd integer.
Solution:
package com.myprograms;
import java.util.Scanner;
public class FermatAlgorithm {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter odd number");
long N = scan.nextLong();
FermatAlgorithm fermatAlgorithm = new FermatAlgorithm();
fermatAlgorithm.findFermatFactor(N);
scan.close();
}
public boolean isSquare(long N)
{
long sqr = (long) Math.sqrt(N);
if (sqr * sqr == N || (sqr + 1) * (sqr + 1) == N)
return true;
return false;
}
public void display(long r1, long r2)
{
System.out.println("\nRoots = "+ r1 +" , "+ r2);
}
public void findFermatFactor(long N)
{
long a = (long) Math.ceil(Math.sqrt(N));
long b2 = a * a - N;
while (!isSquare(b2))
{
a++;
b2 = a * a - N;
}
long r1 = a - (long)Math.sqrt(b2);
long r2 = N / r1;
display(r1, r2);
}
}
Output:
Enter odd number
5959
Roots = 59 , 101
An algorithm due to Fermat can be used to find the largest factor f (less than or equal to squareroot(n)) of an odd integer.
Solution:
package com.myprograms;
import java.util.Scanner;
public class FermatAlgorithm {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter odd number");
long N = scan.nextLong();
FermatAlgorithm fermatAlgorithm = new FermatAlgorithm();
fermatAlgorithm.findFermatFactor(N);
scan.close();
}
public boolean isSquare(long N)
{
long sqr = (long) Math.sqrt(N);
if (sqr * sqr == N || (sqr + 1) * (sqr + 1) == N)
return true;
return false;
}
public void display(long r1, long r2)
{
System.out.println("\nRoots = "+ r1 +" , "+ r2);
}
public void findFermatFactor(long N)
{
long a = (long) Math.ceil(Math.sqrt(N));
long b2 = a * a - N;
while (!isSquare(b2))
{
a++;
b2 = a * a - N;
}
long r1 = a - (long)Math.sqrt(b2);
long r2 = N / r1;
display(r1, r2);
}
}
Output:
Enter odd number
5959
Roots = 59 , 101
No comments:
Post a Comment