Last active
          October 28, 2015 20:59 
        
      - 
      
- 
        Save Prince781/f861ec23c96bcf41daf4 to your computer and use it in GitHub Desktop. 
    get prime factorization
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | /* primes.c | |
| * prints prime factorization of number | |
| * `make primes` | |
| */ | |
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <string.h> | |
| static const char *supers[] = { | |
| "\u2070", | |
| "\u00b9", | |
| "\u00b2", | |
| "\u00b3", | |
| "\u2074", | |
| "\u2075", | |
| "\u2076", | |
| "\u2077", | |
| "\u2078", | |
| "\u2079" | |
| }; | |
| const char *ltosup (long n) { | |
| static char buf[64]; | |
| int i = sizeof(buf)-1; | |
| buf[i] = '\0'; | |
| for (; n != 0; n /= 10) { | |
| int size = strlen (supers [n % 10]); | |
| i -= size; | |
| strncpy(&buf[i], supers[n % 10], size); | |
| } | |
| return &buf[i]; | |
| } | |
| void print_primes (long n) { | |
| long f = 2; | |
| long p; | |
| ldiv_t d; | |
| printf ("1 \u00d7"); | |
| while (f*f <= n) { | |
| p = 0; | |
| while ((d = ldiv(n, f)).rem == 0) { | |
| ++p; | |
| n = d.quot; | |
| } | |
| if (p > 0) | |
| printf (" %ld%s \u00d7", f, ltosup(p)); | |
| if (f == 2) | |
| ++f; | |
| else f += 2; | |
| } | |
| if (n > 1) | |
| printf (" %ld%s\n", n, supers[1]); | |
| else | |
| printf ("\b\b \n"); | |
| } | |
| int main(int argc, char *argv[]) { | |
| if (argc != 2) { | |
| printf("usage: %s [n]\n", argv[0]); | |
| exit(1); | |
| } | |
| print_primes (atol(argv[1])); | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
optimizations in second revision