Factorizer

Please support our C advertiser: Programming Forums - DaniWeb Sister Site
vicky_dev vicky_dev is offline Offline May 25th, 2005, 5:16 am |
0
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.
Quick reply to this message  
C Syntax
  1. #include <stdio.h>
  2. #include <conio.h>
  3.  
  4. int IsPrime( int );
  5. int FindNextPrime( int );
  6.  
  7. int main()
  8. {
  9. int num,divisor = 2;
  10. printf("Enter number:");
  11. scanf("%d",&num );
  12. printf("The prime factors are:\n");
  13.  
  14. while( !IsPrime(num))
  15. {
  16. while(1)
  17. {
  18. if( num%divisor == 0 )
  19. {
  20. printf("%d\n",divisor );
  21. num/=divisor;
  22. break;
  23. }
  24. divisor = FindNextPrime( divisor );
  25. }
  26. }
  27. printf("%d",num);
  28.  
  29. getch();
  30. return 0;
  31. }
  32. //------ End of main() ------
  33.  
  34. int IsPrime( int num ) // Checks whether a number is prime
  35. {
  36. int i;
  37. for( i=2; i<=num/2; i++ )
  38. {
  39. if( num%i == 0 )
  40. return 0;
  41. }
  42. return 1;
  43. }
  44.  
  45. int FindNextPrime( int num ) // Returns next prime number from passed arg.
  46. {
  47. do
  48. {
  49. if( num == 2 )
  50. num++;
  51. else
  52. num+=2;
  53. } while( !IsPrime(num));
  54. return num;
  55. }
0
Reizel Reizel is offline Offline | Jul 8th, 2005
errrm... i just have a question: is it possible not to use isprime to search for the prime factors of a number?
 
0
nlsna17 nlsna17 is offline Offline | Sep 23rd, 2005
can you display if the number is a prime number or not
 
0
bofarull bofarull is offline Offline | Mar 7th, 2006
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
 
 

Message:


Thread Tools Search this Thread



Tag cloud for C
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC