C# Program to Find Prime Factor

You are Here:

What is Prime Factor?

A Prime Factors of a given number is that any prime number other than 1 and itself that exactly divides the given number. For example, the prime factors of 60 is 2, 3, 5

Examples

The following table provides few examples of prime factors of a number.

NumberPrime Factors
555, 11
1002, 5
1862, 3, 31

Find Prime Factor

In the following example, we will find all the Prime factors of the given number (186).

Example

C# Compiler
using System; namespace myApp { class Program { static void Main(string[] args) { int num = 186; int i, j; int count = 0; int flag = 0; Console.Write("Prime factor of {0}:\n", num); for(i=2; i<num; i++) { // check for divisibility if(num % i == 0) { count = 0; // check for prime number for(j=1; j<=i; j++) { if(i % j == 0) count++; } if(count == 2) { flag = 1; Console.Write(i +" "); } } } if(flag == 0) Console.Write("There is no Prime factor for {0} ", num); } } }

Output

Prime factor of 186: 2 3 31

Find Prime Factor of any Given Number

In the following example, we will find a prime factors of any given number.

Example

C# Compiler
using System; namespace myApp { class Program { static void Main(string[] args) { Console.Write("Enter a (int) Number: "); int num = Convert.ToInt32(Console.ReadLine()); int i, j; int count = 0; int flag = 0; Console.WriteLine("\nPrime factor of {0}: ", num); for(i=2; i<num; i++) { // check for divisibility if(num % i == 0) { count = 0; // check for prime number for(j=1; j<=i; j++) { if(i % j == 0) count++; } if(count == 2) { flag = 1; Console.Write(i +" "); } } } if(flag == 0) Console.Write("There is no Prime factor for {0} ", num); } } }

Output

Enter a (int) Number: 25 Prime factor of 25: 5

Reminder

Hi Developers, we almost covered 90% of String functions and Interview Question on C# with examples for quick and easy learning.

We are working to cover every Single Concept in C#.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author