Last active
August 29, 2015 14:00
-
-
Save ad2476/d0e793d4d6ed0c2d635f to your computer and use it in GitHub Desktop.
Largest prime factor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Largest prime factor of number | |
public long primeFactor(long number) { | |
long largestFactor=0; | |
for (long n=2; n<=(int)Math.sqrt(number); n++) { | |
// n is a factor of number | |
if(number%n == 0) { | |
// Is n prime? | |
boolean isPrime=true; | |
for (long i=2; i<=(int)Math.sqrt(n); i++) { | |
if(n%i == 0) { // i is a factor of n | |
isPrime=false; | |
break; | |
} | |
} | |
if(isPrime) { | |
if (n>largestFactor) | |
largestFactor=n; | |
// System.out.println(n); // Print the prime factors | |
} | |
} | |
// Every thousand, let the user know we're still working | |
if(n%1e3==0) System.out.print("."); | |
} | |
System.out.println(""); | |
return largestFactor; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment