如何在计算素因子时改善执行时间

exs*_*ake 5 c math factorial prime-factoring

我必须制作一个程序来找到最大的展示方式!数字(不包括1).

例如:4!= 1x2x3x4 = 1x2x3x2x2.所以你可以使用5个数字的乘积来显示4个!因此输入为4,输出为5. 5是您可以表达4的最大数字量!

简单来说,将素数因子中的因子数量分解,计算它们的数量并显示它们.

我所做的是一个'for'循环,我计算所有主要因素1到'n'和它们的数量.

但我有一个大数字的问题,比如'n'是100000,完成需要8秒.我需要提高速度.

我认为问题在于分解功能.

int factors( int fact )
{
    int i,cont,product=1, control;
    cont=0;
    control=fact;
    for (i= 2;control != product;)
    {
        if ((fact%i == 0))
        {
            cont++;
            fact/=i;
            product*=i;}
        else
        i++;
    }
    return cont;
}
Run Code Online (Sandbox Code Playgroud)

我需要改进它以获得最佳执行时间.或者也许我用来从阶乘数中得到素因子的方法不是一个好的选择?

注意:我不计算100000的值!我只是将所有数字从1分解为10000并计算它们.

BLU*_*IXY 3

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

int *prime;
int prime_n;

void make_prime_table(int n){
    prime = malloc(sizeof(int) * n / 2);
    prime_n =0;
    prime[prime_n++] = 2;
    prime[prime_n++] = 3;
    int i, j;
    for(i = 5; i <= n; i +=2){
        bool is_prime = true;
        for(j = 1; j < prime_n ; ++j){
            int t = prime[j];
            if(t * t > i)
                break;
            if(i % t == 0){
                is_prime = false;
                break;
            }
        }
        if(is_prime)
            prime[prime_n++] = i;
    }
}

int factors(int fact_n ){
    int i, c, p, sum=0;
    for(i = 0; i < prime_n ; ++i){
        c = fact_n;//number of prime in N : (x1 = N / P) + (x2 = x1 / P) + ...
        while(c = c / prime[i]){
            sum += c;
        }
    }
    return sum;
}

int main(void){
    int n = 100000;
    make_prime_table(n);
    int ans = factors(n);
    printf("ans = %d\n", ans);

    free(prime);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

N 中素数 P 的个数!:
十分之二的情况!

1 2 3 4 5 6 7 8 9 10
  *   *   *   *    * # There are 5 number that is divided by 2. 5 = 10 / 2  
      *       *      # Number that can be divided further part of the mark of `*`(5/2).  
              *      # The number of total is the number of `*`.  
Run Code Online (Sandbox Code Playgroud)

*搜索“勒让德定理”