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.

``````#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;
}``````
4
Contributors
3
Replies
4
Views
12 Years
Discussion Span
Last Post by bofarull

errrm... i just have a question: is it possible not to use isprime to search for the prime factors of a number?

can you display if the number is a prime number or not

To nlsna17: prime figures only get null rest (same as integer result) when divided by themselves and by 1. Let it be N, start dividing N/(N-1), N/(N-2), .. until N/2. If ALL these divisions do not render null rest, it is ALL rests > 0, it is ALL Real results, not a single integer result, then N (Integer as well indeed) is prime.
Sure there are faster ways to find out because I am aware of pundits using large primes to hide/cypher data, but I hope the above definition may help as a starting point.

Bofarull

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.