Answers for "prime factors of some numbers"

C#
0

prime factors of a number

public static List<int> PrimeFactors(int n)
{
    if (n == 1)
    {
        return null;
    }
    var list = new List<int>();
    if (n % 2 == 0)
    {
        list.Add(2);

        while (n % 2 == 0)
        {
            n /= 2;
        }
    }

    for (int i = 3; i <= Math.Sqrt(n); i += 2)
    {
        if (n % i == 0)
        {
            list.Add(i);

            while (n % i == 0)
            {
                n /= i;
            }
        }
    }

    if (n > 2)
        list.Add(n);
    return list;
}
Posted by: Guest on April-08-2022

C# Answers by Framework

Browse Popular Code Answers by Language