find largest prime factor using java -
i want find largest prime factor of 600851475143.i wrote following code not getting correct answer. please me ...
public class { public static void main(string[] args) { int arr[]=new int[25]; int large=0; long n=600851475143l; long x=(long) math.sqrt(n); top: for(int i=3;i<x;i=i+2) { if(n%i==0) { n=(long) n/i; for(int j=0;j<25;j++) { arr[j]=i; } break top; } } //system.out.println(arr); int num=arr.length; for(int i=0;i<num-1;i++) { if(arr[i]>arr[i+1]) { large=arr[i]; } else { large=arr[i+1]; } } system.out.println(large); } }
public class lpf { public static void main(string[] args) { int lpf= 2; long num = 600851475143l; while (num > lpf) { if (num % lpf == 0) { num/=lpf; lpf = 2; } else { lpf++; } } system.out.println("largest prime factor " + integer.tostring(lpf)); } }
this simple implementation find largest prime factor of number. way optimize not increment lpf 1 , instead set next highest prime number.
Comments
Post a Comment