/*
* bhatt.umang7@gmail.com
*/
/*
* The prime factors of 13195 are 5, 7, 13 and 29.
* What is the largest prime factor of the number 600851475143 ?
*/
import java.util.ArrayList;
import java.util.List;
public class Problem3
{
/**
* This method will return the ArrayList containing the
* prime-factors of the number passed to the method.
* @param number is the number for which you want to find the prime factors
* @return will return a list which is having prime factors of the number
* passed to the method
*/
public static List<Long> primeFactors(long number)
{
long n = number; // n is the number passed.
List<Long> factors = new ArrayList<>();
// the list which will hold the prime factors of the number passed.
/*
* go up to n \ i increment i
*/
for (long i = 2; i <= n / i; i++)
{
// if the reminder is zero then it is a valid prime factor
while (n % i == 0)
{
// add the currunt number to the list of prime factors
factors.add(i);
n /= i; // n = n / i
// we are changing the nummber itself for
//which we are finding the prime factors
}
}
if (n > 1)
{
factors.add(n);
}
return factors; // return the list to the caller
}
public static void main(String args[])
{
long n = 600851475143L;
// get the list of prime factors by calling the method
List<Long> li = primeFactors(n);
// store the last item of list in the ans variable
long ans = li.get(li.size() - 1);
System.out.println("Ans is " + ans);
// print the answer on the console
}
}
Thursday, January 19, 2012
largest prime factor of the number 600851475143
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment