C program to find prime factors of a number

      The prime factors of a number are the factors which are prime numbers. For example, if we consider the number be 10 then factors of that number are 1, 2, 5 and 10. Among all the numbers 2 and 5 are the prime factors of 10. So prime factors of any number are the factors of that number which are prime. This program finds the prime factors of a given number by finding the factors of that number and then checking whether that is prime or not.

C Program to find Prime factors of a number



Source Code :

#include<stdio.h>
#include<stdbool.h>
bool isPrime(int);
int main(void)
{
	int n, d=2;
	printf("\n Enter the Number: ");
	scanf("%d",&n);        //Step 1
	printf("\n Prime factors of %d is....\n",n);
	for(d=2;d<=n/2;++d)
	  if(n%d==0 && isPrime(d))   //Step 2
	printf("%d ",d);      // Step 4
	return 0;
}
bool isPrime(int x)           //Step 3
{
	int d;
	for(d=2;d<=x/2;++d)    
	    if(x%d==0)
	      return false;
	return true;
}


edit-code-image

Sample Test cases :

1.  Enter the Number: 10
    Prime factors of 10 is.... 2 5

2.  Enter the Number: 9
    Prime factors of 9 is.... 3

Explanation:

Step 1: The number is read from the user using scanf() function.

Step 2: The factors of a number are found using n%d and checked whether that factor is prime or not using ‘isPrime()’ function.

Step 3: isPrime() function returns true if given factor is prime number otherwise it returns false.

Step 4: Finally the factors which are prime numbers are printed on the output screen using printf() function.
More Content:Explore More
More about prime factors:Prime Factors