Sunday, 17 March 2019

C Program to find prime factors of a given number

Write a C Program to Find Prime Factors Of a Given number from the User


In this C program, we have to find the prime factors of a given number. The user will input the number and after all the calculation of the C program. The program should return all the prime factors of the number.


Let's see how we can make this C program.

C program to Find Prime Factors Of a Given number


A prime number is a number which is divisible by 1 and itself. So if we take an example,

7 is divisible by 1 and 7. So it is a prime number.

In this C program we have to take the number n from the user and divide it by every number from 2 to the number n. If n gets divided by any other number then it is not a prime number and If n doesn't get divided by any other number then it is a prime number.

Code for the C Program to find Prime Factors of a Number



#include<stdio.h>
#include<conio.h>
void main()
{

     int n,x;
     clrscr();
     printf("Enter a number to find its prime factors : ");
     scanf("%d",&n);
     if(n<=1)
     {
          printf("Enter a value greater than 1, ");
          getch();
          exit(0);
      }
      x=2;
      do
      {
            if(n%x==0)
            {
                printf("%d\t",x);
                n/=x;
             }
            else
                 x++;
      }
      while(x<=n);
      getch();
}





Output of the C Program



Output :
Enter a number to find its prime factors :
72
The prime factors of 72 are :
2 2 2 3 3

No comments:

Post a Comment