home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / snip9707.zip / IFACTOR.C < prev    next >
C/C++ Source or Header  |  1997-07-05  |  1KB  |  70 lines

  1. /* +++Date last modified: 05-Jul-1997 */
  2.  
  3. /*
  4. ** ifactor.c -- print prime factorization of a number
  5. **
  6. ** Ray Gardner -- 1985 -- public domain
  7. */
  8.  
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11.  
  12. int prevfact = 0;
  13. void factor (long);
  14. void show (long, int);
  15.  
  16. main (int argc, char *argv[])
  17. {
  18.       while ( --argc )
  19.             factor(atol(*++argv));
  20.       return 0;
  21. }
  22.  
  23. void factor (long n)
  24. {
  25.       long d;
  26.       int k;
  27.       long n0 = n;
  28.       prevfact = 0;
  29.  
  30.       printf("%ld  ",n);
  31.       if ( n < 2 )
  32.       {
  33.             printf("is less than 2.\n");
  34.             return;
  35.       }
  36.       else if ( n > 2 )
  37.       {
  38.             d = 2;
  39.             for ( k = 0; n % d == 0; k++ )
  40.                   n /= d;
  41.             if ( k )
  42.                   show(d,k);
  43.             for ( d = 3; d * d <= n; d += 2 )
  44.             { 
  45.                   for ( k = 0; n % d == 0; k++ )
  46.                         n /= d;
  47.                   if ( k )
  48.                         show(d,k);
  49.             }
  50.       }
  51.       if ( n > 1 )
  52.       {
  53.             if ( n == n0 )
  54.                   printf(" is prime");
  55.             else  show(n,1);
  56.       }
  57.       printf("\n");
  58. }
  59.  
  60. void show (long d, int k)
  61. {
  62.       if ( prevfact )
  63.             printf(" * ");
  64.       else  printf(" = ");
  65.       prevfact++;
  66.       printf("%ld",d);
  67.       if ( k > 1 )
  68.             printf("^%d",k);
  69. }
  70.