Monday, June 18, 2012

To print the prime factors of a number


/* Program to print the prime factors of a number */

#include<stdio.h>

#include<conio.h>

#include<math.h>

void main()

{

  int n,i;

  clrscr();

  printf("Enter any number:\n");

  scanf("%d",&n);

  printf("\n\nPrime factors are:\n");

  /* Print the numberof 2s that divide n */

  while(n%2==0)

  {

    printf("\n%d",2);

    n=n/2;

  }

  /* n is odd at this point */

  for(i=3;i<=sqrt(n);i=i+2)

  {

    while(n%i==0)

    {

      printf("\n%d",i);

      n=n/i;

    }

  }

  /* To handle prime number greater than 2 */

  if(n>2)

    printf("\n%d",n);

  getch();

}

 

OUTPUT

 

Enter any number:

315

 

 

Prime factors are:

 

3

3

5

7

 

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.