Reputation: 101
Optimizing code for finding the largest prime factor for a given number? Below code worked for small input case but didn't work for large input case
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
long n = in.nextLong();
long i=n;
if(n%2==0)
i=i-1;
for(;i>=1;i-=2)
{
if(n%i==0&&prime(i))
break;
}
if(n%2==0&&i<2)
System.out.println(2);
else
System.out.println(i);
}
public static boolean prime(long n)
{
if(n%2==0)
return false;
for(long i=3;i<=Math.sqrt(n);i+=2)
{
if(n%i==0)
return false;
}
return true;
}
Upvotes: 1
Views: 251
Reputation: 318
I've written the code below and it works for big numbers very fast.
public static void main(String[] args) {
long result = largestPrimeFactor(600851475143L);
System.out.println("Result : " + result);
}
public static long largestPrimeFactor(long num) {
long largest = -1;
long i = 2;
while (num > 1) {
if (num % i == 0) {
num /= i;
if (largest < i)
largest = i;
} else {
i++;
}
}
return largest;
}
Upvotes: 0
Reputation: 157
Try this
public long largestPrime(long n){
long ans = 0;
while(n % 2 == 0){
n/=2;
ans = Math.max(ans, 2);
}
for(long i = 3; i*i <= n; i++){
while(n%i == 0){
n /= i;
ans = Math.max(ans, i);
}
}
if(n > 1) ans = Math.max(n, ans);
return ans;
}
Upvotes: 1