You might also want to read these related articles first:
The following C function computes and prints the prime decomposition of the integer received as argument in the function call.
/*
* Description:
* Computes the prime factorization of an integer
* Parameters:
* n - the integer to be factorized
*/
void Factorization(int n)
{
int d = 2, pow = 0;
printf("\n\tInteger factorization of %d: ",n);
//the number to be factorized n is greater than 1 and
//the current integer to be tested as a prime factor d is lower than n
while(n > 1)
{
pow = 0;
//while d is a valid prime factor
while(n%d == 0)
{
pow++;//counting the number of times d divides n
n /= d;
}
if(pow != 0)//if d divides n at least once
{
printf("%d",d);//printing d
if(pow != 1)//if d divides n more than once
{
printf("^%d",pow);//printing the power of d
}
printf("*");
}
d++;
}
printf("\b ");
}
Example: This C program reads a number from keyboard and, using the function defined above, prints the number's prime factorization.
#include<stdio.h>
#include<conio.h>
void Factorization(int n);
int main(void)
{
int n = 0;
printf("\n Enter the number to be factorized: ");
scanf("%d",&n);
Factorization(n);
getch();
return 0;
}
Output:

No comments:
Post a Comment