C Program to Find Prime factors of a given number

Ans: 

In this tutorial you will learn writing program to print all possible prime factor of a given number in C.

Before moving on writing program lets know what is prime factor?

What is Prime Factor?

It is a combination of two words “Prime” and “Factor”.

Prime means a number which can be only divisible by 1 and number itself.

For Example: 1, 2, 3, 5, etc.

And Factor is a part of a number which multiplication gives you the original number.

For example:

  2*3 = 6

Here 2 and 3 are the prime factor of 6.

Prime factor is basically all factor of a number that should be prime number.

How our program will behave?

The prime factor calculation program will take a number as a input and in result it will print all outputs with prime factors.

For example if you want to calculate the prime factor of a number 16 then you should give 16 as an input.

And After calculation program should return 2, 2, 2, 2 as an output.

Program to find all Prime Factor of a given number in C

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main() {
  int i = 0, n;
  printf("Please enter a number: ");
  scanf("%d", & n);
  printf("Prime factors of a given number \n");
  while (n % 2 == 0) {
    printf("%d, ", 2);
    n = n / 2;
  }
  for (i = 3; i <= sqrt(n); i = i + 2) {
    while (n % i == 0) {
      printf("%d,", i);
      n = n / i;
    }
  }
  if (n > 2) {
    printf("%d, ", n);
  }
  getch();
}

Output 1:

Please enter a number: 16
Prime factors of a given number 
2, 2, 2, 2, 

Output 2:

Please enter a number: 76
Prime factors of a given number 
2, 2, 19, 

Explanation of the above program

  • Above program is little bit logical but not hard to understand.
  • We have 4 variables i, j, n, temp. i and temp is initialized with 0.
  • First while loop will print 2 as a prime factor for each time when a number can be divide by 2.
  • Now the next for loop will check if  any odd number can divide a number.
  • And last if statement is to print those number as a prime factor which square root is less than 3.

I hope it has helped you to understand prime factor program using C Language.

Leave a Comment