Wednesday, December 23, 2009

Prime factorization of a given integer


// Prime factorization.cpp : Defines the entry point for the console application.


//


 


#include "stdafx.h"


 


 


int _tmain(int argc, _TCHAR* argv[])


{


      int num,k=0,i=1,pri[100],j,count=0,tru=0,fac[100],ans[100],m,n;


      printf("Enter the number: ");


      scanf("%d",&num);


      //Generating the first 100 prime numbers and storing them in the pri[] array.


      while(count<100)


      {


            tru=0;


            i++;


            for(j=2;j<=i/2;j++)


            {


                  if(i%j==0)


                  {


                        tru=1;


                        break;


                  }


            }


            if(tru!=1)


            {


                  pri[count]=i;


                  count++;


            }


      }


      /*printf("The prime numbers are:\n");


      for(i=0;i<count;i++)


      {


            printf("%d,",pri[i]);


      }*/


      i=0;tru=0;


      //Doing the prime factorization.


      while(num>1)


      {


            j=0;tru=0;


            while(num%pri[i]==0)


            {


                  tru=1;


                  num=num/pri[i];


                  j++;


            }


            if(tru==1)


            {


                  fac[k]=j;


                  ans[k]=pri[i];


                  k++;


            }


            i++;


      }


      printf("The prime factorization is:\n");


      //Printing the prime factorization in the correct format.


      for(m=0;m<k;m++)


      {


            for(n=0;n<fac[m];n++)


            {


                  if(m!=0 && n==0)


                        printf("*");


                  printf("%d",ans[m]);


                  if(n!=fac[m]-1)


                        printf("*");


            }


      }


      printf("\n");


      return 0;


}


 


Enter the number: 36
The prime factorization is:
2*2*3*3
Press any key to continue . . .

No comments:

Post a Comment