Skip to content

Instantly share code, notes, and snippets.

@rfaisal
Last active December 19, 2015 09:49
Show Gist options
  • Save rfaisal/5935970 to your computer and use it in GitHub Desktop.
Save rfaisal/5935970 to your computer and use it in GitHub Desktop.
The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ?
public class LargestPrimeFactor {
private long num;
public LargestPrimeFactor(long num){
this.num=num;
}
public long calculate(){
for(long i=1;i<=num/2;i++)
if(num%i==0)
if(isPrime(num/i))
return num/i;
return 1;
}
private static boolean isPrime(long num){
for(long i=2;i<=(long)Math.sqrt(num);i++){
if(num%i==0) return false;
}
return true;
}
}
public class LargestPrimeFactorTest {
@Test
public void testCalculate() {
assertEquals(29, new LargestPrimeFactor(13195).calculate());
assertEquals(6857,new LargestPrimeFactor(600851475143L).calculate());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment