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

  1. /* +++Date last modified: 05-Jul-1997 */
  2.  
  3. /*
  4. ** factor.c -- print prime factorization of a number
  5. ** Ray Gardner -- 1985 -- public domain
  6. ** Modified Feb. 1989 by Thad Smith > public domain
  7. **
  8. ** This version takes numbers up to the limits of double precision.
  9. */
  10.  
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <math.h>
  14.  
  15. int prevfact = 0;
  16. void factor (double);
  17. void show (double, int);
  18.  
  19. main (int argc, char *argv[])
  20. {
  21.       while ( --argc )
  22.             factor(atof(*++argv));
  23.       return 0;
  24. }
  25.  
  26. void factor (double n)
  27. {
  28.       double d;
  29.       int k;
  30.  
  31.       prevfact = 0;
  32.  
  33.       d = n+1;     /* test for roundoff error */
  34.       if (n+3 != d+2)
  35.       {
  36.             printf("%0.0f is too large to process.\n", n);
  37.             return;
  38.       }
  39.       if (fmod(n,1.) != 0.0)
  40.       {
  41.             printf("%f is not an integer.\n",n);
  42.             return;
  43.       }
  44.       printf("%0.0f  ",n);
  45.       if ( n < 2. )
  46.       {
  47.             printf("is less than 2.\n");
  48.             return;
  49.       }
  50.       else if ( n > 2. )
  51.       {
  52.             d = 2;
  53.             for ( k = 0; fmod(n,d) == 0.0; k++ )
  54.                   n /= d;
  55.             if ( k )
  56.                   show(d,k);
  57.             for ( d = 3; d * d <= n; d += 2 )
  58.             {
  59.                   for ( k = 0; fmod(n,d) == 0.0; k++ )
  60.                         n /= d;
  61.                   if ( k )
  62.                         show(d,k);
  63.             }
  64.       }
  65.       if ( n > 1 )
  66.       {
  67.             if ( ! prevfact )
  68.                   printf(" is prime");
  69.             else  show(n,1);
  70.       }
  71.       printf("\n");
  72. }
  73.  
  74. void show (double d, int k)
  75. {
  76.       if ( prevfact )
  77.             printf(" * ");
  78.       else  printf(" = ");
  79.       prevfact++;
  80.       printf("%0.0f",d);
  81.       if ( k > 1 )
  82.             printf("^%d",k);
  83. }
  84.