Prime factors of integer

Write a program to get the prime factor of given number.

for example:

Input:
35

Output:
7,5 

Solution:

using System;
using System.Collections.Generic;

namespace PrimeFactor
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("Enter a number:");
            var num1 = Convert.ToInt32(Console.ReadLine());

            var result = PrimeFactors(35);

            Console.WriteLine($"Prime factor of {num1}:");
            foreach (var i in result)
            {
                Console.WriteLine(i);
            }

            Console.ReadLine();
        }

        public static List<int> PrimeFactors(int n)
        {
            var result = new List<int>();
            while (n % 2 == 0)
            {
                Console.Write(2 + " ");
                n /= 2;
            }

            for (var i = 3; i <= Math.Sqrt(n); i += 2)
            {
                while (n % i == 0)
                {
                    result.Add(i);
                    n /= i;
                }
            }

            if (n > 2)
                result.Add(n);

            return result;
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *