Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prime Factors In C#

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();



    }
}
like image 765
Aliza Avatar asked May 03 '11 16:05

Aliza


People also ask

What is prime factor in C?

Master C and Embedded C Programming- Learn as you go Prime Factor is a prime number which is the factor of the given number. Factor of a number are the numbers that are multiplied to get the given number.

How do you find prime factors?

The simplest algorithm to find the prime factors of a number is to keep on dividing the original number by prime factors until we get the remainder equal to 1. For example, prime factorizing the number 30 we get, 30/2 = 15, 15/3 = 5, 5/5 = 1. Since we received the remainder, it cannot be further factorized.


3 Answers

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!

like image 172
Vilx- Avatar answered Oct 26 '22 23:10

Vilx-


public static List<int> Generate(int number)
{
    var primes = new List<int>();

    for (int div = 2; div <= number; div++)
        while (number % div == 0)
        {
            primes.Add(div);
            number = number / div;
        }
    
    return primes;
}

If you want to learn steps of development you can watch video here.

like image 31
Bayram Üçüncü Avatar answered Oct 26 '22 23:10

Bayram Üçüncü


You can go one better as the divisor can never be larger than the square root of the number.

 for(int div = 2; div <= Math.Sqrt(number); div++)
like image 27
John Conacher Avatar answered Oct 27 '22 01:10

John Conacher