Prime factorization of a factorial

后端 未结 6 1475
陌清茗
陌清茗 2021-01-05 17:38

I need to write a program to input a number and output its factorial\'s prime factorization in the form:

4!=(2^3)*(3^1)

5!=(2^3)*(3^1)*(5^1)
6条回答
  •  遥遥无期
    2021-01-05 17:58

    You can use O(n/2 log log n) algorithm using only sums (no need precalc primes).

    This is a sieve using relation

    f = a * b  ~>  f^k = a^k * b^k
    

    then, we reduce all initial factors 1 * 2 * 3 * ... * n moving k from big numbers to small numbers.

    Using Sieve of Atkin the Will Ness algorithm could be better for very big n if not, I think it could be better

    #include 
    #include 
    
    int main(int argc, char **argv) {
      int n = atoi(argv[1]);
      int *p = (int *) malloc(sizeof(int) * (n + 1));
      int i, j, d;
      for(i = 0; i <= n; i++)
        p[i] = 1;
      for(i = n >> 1; i > 1; i--)
        if(p[i]) {
          for(j = i + i, d = 2; j <= n; j += i, d++) {
            if(p[j]) {
              p[i] += p[j];
              p[d] += p[j];
              p[j] = 0;
            }
          }
        }
      printf("1");
      for(i = 2; i <= n; i++)
        if(p[i])
          printf(" * %i^%i", i, p[i]);
      printf("\n");
      return 0;
    }
    

提交回复
热议问题