ccplusplus.com
Learn C, C++ Concepts
Monday, September 12, 2011
find prime factors of a number in c
/****************************************************** * File : find-checkPrime-factor.c * Author : Saurabh Gupta * Desc : finds the checkPrime factor of a number * Source : http://saurabhgupta0527.blogspot.com/ * Created : AM 08:42 12 September 2011 * Note : *****************************************************/ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <math.h> /* * function definition or signature */ int getPrimeFactor(int); // calculate the prime factor int checkPrime(int ); // check numbner is prime or not int main (int argc, char **argv) { int nNumPrimeFactor; int checkPrime(int nNumPrimeFactor); int getPrimeFactor(int nNumPrimeFactor); printf("Enter the nNumPrimeFactor whose prime factors are to be calculated:"); scanf ("%d", &nNumPrimeFactor); getPrimeFactor(nNumPrimeFactor); return 0; } //The following is the function that detects a Prime nNumPrimeFactor. int checkPrime(int num) { int i, ifprime; for (i=2; i<=num-1; i++) { if (num%i==0) { ifprime=0; } else { ifprime=1; } } return (ifprime); } //The following function prints the prime factors of a nNumPrimeFactor. int getPrimeFactor(int num) { int factor, ifprime; for (factor=2; factor<=num;) { checkPrime(factor); //so that the factors are only prime and nothing else. if (ifprime) { //diving by all the prime numbers less than the nNumPrimeFactor itself. if (num%factor==0) { printf("%d\n", factor); num=num/factor; continue; } else { factor++;//this cannot be made a part of the for loop } } } return 0; } /* * OUTPUT * [sgupta@rhel54x64 c]$ [sgupta@rhel54x64 c]$ gcc find-prime-factor.c -o find-prime-factor [sgupta@rhel54x64 c]$ ./find-prime-factor Enter the nNumPrimeFactor whose prime factors are to be calculated:11 11 [sgupta@rhel54x64 c]$ */
See also
Other popular tricky C Sample Codes and language Concep
t
.
No comments:
Post a Comment
Newer Post
Older Post
Home
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment