Skip to content

Instantly share code, notes, and snippets.

@rmfbarker
Created August 23, 2013 05:59
Show Gist options
  • Save rmfbarker/6315967 to your computer and use it in GitHub Desktop.
Save rmfbarker/6315967 to your computer and use it in GitHub Desktop.
Work out the prime factors from a given integer and also the number of factors for that integer. Adopted from http://introcs.cs.princeton.edu/java/13flow/Factors.java.html
import java.util.*;
public class Factors {
public static List<Long> primeFactors(long n) {
List<Long> result = new ArrayList<Long>();
// for each potential factor i
for (long i = 2; i*i <= n; i++) {
// if i is a factor of N, repeatedly divide it out
while (n % i == 0) {
result.add(i);
n = n / i;
}
}
// if biggest factor occurs only once, n > 1
if (n > 1) result.add(n);
return result;
}
public static int numberOfFactors(long n) {
List<Long> primeFactors = primeFactors(n);
HashSet<Long> uniqueFactors = new HashSet<Long>(primeFactors);
int sum = 1;
for (long l : uniqueFactors) {
int occurs = Collections.frequency(primeFactors, l);
sum *= occurs + 1;
}
return sum;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment