Created
February 8, 2015 04:22
-
-
Save dmnugent80/4d05f97c4b44ef3de524 to your computer and use it in GitHub Desktop.
Print All Prime Factors
This file contains hidden or 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
public class PrimeTest | |
{ | |
public static void main(String[] args) | |
{ | |
PrintPrimeFactors myObject = new PrintPrimeFactors(); | |
myObject.primeFactors(600851475143L); | |
} | |
} | |
public class PrintPrimeFactors | |
{ | |
public void primeFactors(long n) | |
{ | |
// Print the number of 2s that divide n | |
while (n%2 == 0) | |
{ | |
System.out.print(String.format("%-8d", 2)); | |
n = n/2; | |
} | |
// n must be odd at this point. So we can skip one element (Note i = i +2) | |
for (int i = 3; i * i <= n; i = i+2) | |
{ | |
// While i divides n, print i and divide n | |
while (n%i == 0) | |
{ | |
System.out.print(String.format("%-8d", i)); | |
n = n/i; | |
} | |
} | |
// This condition is to handle the case whien n is a prime number | |
// greater than 2 | |
if (n > 2){ | |
System.out.print(String.format("%-8d", n)); | |
} | |
} | |
} | |
/*output: | |
71 839 1471 6857 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment