C Program to Find Prime Factor

Last Updated:

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
55 5, 11
100 2, 5
186 2, 3, 31

Find Prime Factor

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

Example

C Compiler
#include <stdio.h> int main() { int num = 186; int i, j; int count = 0; int flag = 0; 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) { if(flag == 0) printf("Prime factor of %d: \n", num); printf("%d ", i); flag = 1; } } } if(flag == 0) printf("There is no Prime factor for %d ", num); return 0; }

Find Prime Factor of any Given Number

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

Example

C Compiler
#include <stdio.h> int main() { int num, i, j; int count = 0; int flag = 0; printf("Enter a (int) Number: "); scanf("%d", &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) { if(flag == 0) printf("\nPrime factor of %d:\n", num); printf("%d ", i); flag = 1; } } } if(flag == 0) printf("There is no Prime factor for %d ", num); return 0; }

Share this Page

Meet the Author