【问题标题】:How to optimize code for finding Amicable Pairs如何优化代码以查找友好对
【发布时间】:2010-11-18 18:09:33
【问题描述】:

请查看我用来查找所有 Amicable Pairs (n, m), n http://tutoree7.pastebin.com/wKvMAWpT。找到的对:http://tutoree7.pastebin.com/dpEc0RbZ.

我发现现在每增加一百万需要在我的笔记本电脑上使用 24 分钟。我希望有大量的 n 可以提前过滤掉。这很接近,但没有雪茄:不以“5”结尾的奇数 n。到目前为止,只有一对反例,但数量太多了:(34765731, 36939357)。那作为过滤器将过滤掉所有 n 的 40%。

我希望有一些想法,不一定是用于实现它们的 Python 代码。

【问题讨论】:

  • 你这样做是为了欧拉计划还是其他竞赛?
  • @XML 否。作为优化练习。到目前为止,我一直致力于优化功能。
  • @belisarius:但没有使用过滤器来查找这些对?无论如何,非常有趣的网站——不仅是 ch。 9!

标签: optimization number-theory


【解决方案1】:

这是一篇很好的文章,总结了 finding amicable pairs

的所有优化技术

与sample C++ code

它在不到一秒的时间内找到所有 10^9 以内的友好数字。

【讨论】:

    【解决方案2】:
    #include<stdio.h>
    #include<stdlib.h>
    int sumOfFactors(int );
    
    int main(){
        int x, y, start, end;
        printf("Enter start of the range:\n");
        scanf("%d", &start);
        printf("Enter end of the range:\n");
        scanf("%d", &end);
    
        for(x = start;x <= end;x++){
            for(y=end; y>= start;y--){
                if(x == sumOfFactors(y) && y == sumOfFactors(x) && x != y){
                    printf("The numbers %d and %d are Amicable pair\n", x,y);
                }
            }
        }   
        return 0;
    }
    
    int sumOfFactors(int x){
        int sum = 1, i, j;
        for(j=2;j <= x/2;j++){
            if(x % j == 0)
                sum += j;
        }
        return sum;
    }
    

    【讨论】:

    • 提问者提到他们正在使用 Python - 最好用那种语言来回应。 :)
    【解决方案3】:
    def findSumOfFactors(n):
        sum = 1
        for i in range(2, int(n / 2) + 1):
            if n % i == 0:
                sum += i
        return sum
    
    start = int(input())
    end = int(input())
    
    for i in range(start, end + 1):
        for j in range(end, start + 1, -1):
            if i is not j and findSumOfFactors(i) == j and findSumOfFactors(j) == i and j>1:
                print(i, j)
    

    【讨论】:

      猜你喜欢
      • 2015-06-02
      • 1970-01-01
      • 2016-05-07
      • 2017-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多