【问题标题】:How to improve execution time when calculating prime factors如何在计算素数时提高执行时间
【发布时间】:2014-08-11 00:22:03
【问题描述】:

我必须做一个程序来找到显示n的最大方式!数字(不包括 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;
}

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

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

【问题讨论】:

  • 4! 不等于 1x2x3x4x5
  • 澄清一下,您要计算100000! 的值?你有什么想法just how big that number is
  • 顺便说一句,您可以将其视为算术(或数论)数学练习。提示:你可能不需要计算 100! 来获得它的最大素因子。
  • 如果是 7!是输入。输出是 8 (2x3x2x2x5x2x3x7)...我不是在计算 7 的值!,只是主要因素的数量。
  • @FiddlingBits 告诉我的老师哈哈。我认为如果你不关心需要多少时间,这不是一个很难解决的问题。执行时间不是作业的要求,我只是痴迷于改善那个时间。

标签: c math factorial prime-factoring


【解决方案1】:
#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;
}

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 `*`.  

*搜索“勒让德定理”

【讨论】:

  • 嗯...这是完整的答案...我非常感谢您,但我觉得如果我阅读或复制您的答案,我会学到任何东西...如果您给我的提示如何去获得更好的时间我会非常感激。
  • 好吧,我还没有得到那个定理(哈哈),但是我从你那里得到了制作一个素数表以在代码中使用的想法(而不是调用一个函数来查看一个数字每次都是素数),从 8 秒我将时间提高到 1 秒,所以谢谢你!这可能不是很多,但我更喜欢按我的方式走,而不是复制任何代码......再次感谢!
  • 好的,我得到了定理,现在只需要几分之一秒。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2015-06-05
  • 2022-01-21
  • 1970-01-01
  • 2014-09-13
  • 2013-04-30
  • 1970-01-01
  • 2021-07-15
  • 1970-01-01
相关资源
最近更新 更多