Mid Coding

Find all prime factors of a number?

public List<int> PrimeFactors(int n) {

List<int> factors = new List<int>();

// Print the number of 2s that divide n

while (n % 2 == 0) {

factors.Add(2);

n /= 2;

// n must be odd at this point

for (int i = 3; i * i <= n; i += 2) {

while (n % i == 0) {

factors.Add(i);

n /= i;

Follow on:

// If n is a prime number > 2

if (n > 2) {

factors.Add(n);

return factors;

Explanation:

We repeatedly divide by 2, then check odd factors up to √n. If leftover n > 2, it's prime.

More from C# Programming Tutorial

All questions for this course