如何加快可和数字算法? [英] How do I speed up my Amicable number algorithm?

查看:82
本文介绍了如何加快可和数字算法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

完成100,000个限制需要很长时间.

It take pretty long time to complete the limit(n) of 100,000.

我怀疑问题出在 CalculateAmicable()上,该数字越来越大,需要花费更多的时间进行计算.我可以做些什么来使其加快速度呢?

I suspect that the problem is with the CalculateAmicable() where the number get bigger and it take more time to calculate. What can I change to make it speed up faster than this?

public static void Main (string[] args)
    {
        CheckAmicable (1, 100000);

    }

    public static int CheckAmicable(int start, int end)
    {
        for (int i = start; i < end; i++) {

            int main = CalculateAmicable (i); //220
            int temp = CalculateAmicable (main); //284
            int compare = CalculateAmicable (temp); //220
            if (compare == main) {
                if (main != temp && temp == i) {
                    Console.WriteLine (main + " = " + temp + " = " + compare + " i: " + i);
                    i = compare + 1;
                }
            }
        }
        return 0;
    }

    public static int CalculateAmicable(int number)
    {
        int total = 0;
        for (int i = 1; i < number; i++) {
            if (number%i == 0){
                total += i;
            }
        }
        return total;
    }

注意:英语不是我的母语!

Note: English is not my first language!

推荐答案

是的,CalculateAmicable效率低的-O(N)复杂性-因此,您可以进行N测试1e5 * 1e5 == 1e10- 百亿操作很慢. 将复杂度降低到O(log(N))的方案是

Yes, CalculateAmicable is inefficient - O(N) complexity - and so you have fo N tests 1e5 * 1e5 == 1e10 - ten billions operations which is slow. The scheme which reduces complexity to O(log(N)) is

  int n = 100000;

  //TODO: implement IList<int> GetPrimesUpTo(int) yourself
  var primes = GetPrimesUpTo((int)(Math.Sqrt(n + 1) + 1));

  // Key - number itself, Value - divisors' sum 
  var direct = Enumerable
    .Range(1, n)
    .AsParallel()
    .ToDictionary(index => index, 
                  index => GetDivisorsSum(index, primes) - index);

  var result = Enumerable
    .Range(1, n)
    .Where(x => x < direct[x] && 
                direct.ContainsKey((int) direct[x]) &&
                direct[(int) direct[x]] == x)
    .Select(x => $"{x,5}, {direct[x],5}");

  Console.Write(string.Join(Environment.NewLine, result));

结果不到一秒钟(Core i7 3.2Ghz .Net 4.6 IA-64):

The outcome is within a second (Core i7 3.2Ghz .Net 4.6 IA-64):

  220,   284
 1184,  1210
 2620,  2924
 5020,  5564
 6232,  6368
10744, 10856
12285, 14595
17296, 18416
63020, 76084
66928, 66992
67095, 71145
69615, 87633
79750, 88730

详细信息GetDivisorsSum:

private static long GetDivisorsSum(long value, IList<int> primes) {
  HashSet<long> hs = new HashSet<long>();

  IList<long> divisors = GetPrimeDivisors(value, primes);

  ulong n = (ulong) 1;
  n = n << divisors.Count;

  long result = 1;

  for (ulong i = 1; i < n; ++i) {
    ulong v = i;
    long p = 1;

    for (int j = 0; j < divisors.Count; ++j) {
      if ((v % 2) != 0)
        p *= divisors[j];

      v = v / 2;
    }

    if (hs.Contains(p))
      continue;

    result += p;

    hs.Add(p);
  }

  return result;
}

GetPrimeDivisors:

private static IList<long> GetPrimeDivisors(long value, IList<int> primes) {
  List<long> results = new List<long>();

  int v = 0;
  long threshould = (long) (Math.Sqrt(value) + 1);

  for (int i = 0; i < primes.Count; ++i) {
    v = primes[i];

    if (v > threshould)
      break;

    if ((value % v) != 0)
      continue;

    while ((value % v) == 0) {
      value = value / v;

      results.Add(v);
    }

    threshould = (long) (Math.Sqrt(value) + 1);
  }

  if (value > 1)
    results.Add(value);

  return results;
}

这篇关于如何加快可和数字算法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆