How to find the prime factors of a number in C#

1 Answer

0 votes
using System;
 
class Program
{
    static void printPrimeFactor(int n) {
        int div = 2;
        while (n != 0) {
            if (n % div != 0) {
                div = div + 1;
            }
            else {
                Console.Write(div + ", ");
                n = n / div;
                if (n == 1) {
                    break;
                }
            }
        }
        Console.WriteLine();
    }
    static void Main() {
        int n = 124;
           
        printPrimeFactor(n); // 2 x 2 x 31
        printPrimeFactor(288); // 2 x 2 x 2 x 2 x 2 x 3 x 3
        printPrimeFactor(1288); // 2 x 2 x 2 x 7 x 23
        printPrimeFactor(4008); // 2 x 2 x 2 x 3 x 167
    }
}
 
 
 
/*
run:
 
2, 2, 31, 
2, 2, 2, 2, 2, 3, 3, 
2, 2, 2, 7, 23, 
2, 2, 2, 3, 167, 
 
*/

 

 



answered Jul 17, 2020 by avibootz
edited Aug 18, 2023 by avibootz

Related questions

1 answer 91 views
1 answer 100 views
1 answer 71 views
1 answer 124 views
1 answer 118 views
1 answer 120 views
1 answer 130 views
...