DEV Community

Discussion on: Project Euler #3 - Largest Prime Factor

Collapse
 
jacklangcreator profile image
Sagnik Ray • Edited

java is cool

static long IsPrime(long n){
int counter = 2;
long newval = n;
long larfact = 0;
while(counter*counter <= n){
if(newval % counter == 0){
newval = newval/counter;
larfact = counter;
}
else{
counter++;
}
}
if(newval > larfact){
larfact = newval;
}
return larfact;

but 600851475143 is coming under the range of the "long" data type of java but still it works for any value below it .
THE APPROACH IS PRETTY SIMPLE :
I used the the "Fundamental Theorem of Arithmetic" which states That Any Integer greater than 1 is either a prime number or product of prime numbers.
For example:
12
we start with smallest prime number 2.
the 12/2 = 6 which means that 2 is the prime factor 12.
If we try again by dividing the result by 2
6/2 = 3 . 3 is also a prime number . So the complete factorization is 2,2,3.

I have implemented this logic in the above code This works really fast .I think this code can be improved
a little bit Please some one suggest me.

Hope You like The implementation ;)