Skip to content

Instantly share code, notes, and snippets.

@ad2476
Last active August 29, 2015 14:00
Show Gist options
  • Save ad2476/d0e793d4d6ed0c2d635f to your computer and use it in GitHub Desktop.
Save ad2476/d0e793d4d6ed0c2d635f to your computer and use it in GitHub Desktop.
Largest prime factor
// 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