Prime Factors In C#

Aliza picture Aliza · May 3, 2011 · Viewed 28k times · Source

I want to create a program in C# 2005 which calculates prime factors of a given input. i want to use the basic and simplest things, no need to create a method for it nor array things etc. just simple modulus. is there any code which fulfills what i desire?

here is the code for finding simple factors, i need this code to be modified to calculate prime factors

class Program
{
    static void Main(string[] args)
    {
        int a, b;
        Console.WriteLine("Please enter your integer: ");
        a = int.Parse(Console.ReadLine());
        for (b = 1; b <= a; b++)
        {
            if (a % b == 0)
            {
                Console.WriteLine(b + " is a factor of " + a);
            }
        }
        Console.ReadLine();



    }
}

Answer

Vilx- picture Vilx- · May 3, 2011
int a, b;
Console.WriteLine("Please enter your integer: ");
a = int.Parse(Console.ReadLine());

for (b = 2; a > 1; b++)
    if (a % b == 0)
    {
        int x = 0;
        while (a % b == 0)
        {
            a /= b;
            x++;
        }
        Console.WriteLine($"{b} is a prime factor {x} times!");
    }
Console.WriteLine("Th-Th-Th-Th-Th-... That's all, folks!");

Works on my machine!