This program prints the prime factors of a number. Eg. 56=2x2x2x7 .I've heard its really important and stuff.I believe it is really efficient and simple. Uses two functions : one to check if a number is prime and other to return the next prime number.
Factorizer
#include <stdio.h>
#include <conio.h>
int IsPrime( int );
int FindNextPrime( int );
int main()
{
int num,divisor = 2;
printf("Enter number:");
scanf("%d",&num );
printf("The prime factors are:\n");
while( !IsPrime(num))
{
while(1)
{
if( num%divisor == 0 )
{
printf("%d\n",divisor );
num/=divisor;
break;
}
divisor = FindNextPrime( divisor );
}
}
printf("%d",num);
getch();
return 0;
}
//------ End of main() ------
int IsPrime( int num ) // Checks whether a number is prime
{
int i;
for( i=2; i<=num/2; i++ )
{
if( num%i == 0 )
return 0;
}
return 1;
}
int FindNextPrime( int num ) // Returns next prime number from passed arg.
{
do
{
if( num == 2 )
num++;
else
num+=2;
} while( !IsPrime(num));
return num;
}
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.