需要帮助优化算法

编程入门 行业动态 更新时间:2024-10-25 14:33:26
本文介绍了需要帮助优化算法 - 2000000下的所有质数之和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图做一个项目欧拉问题。

我要找的所有质数的总和200万之下。

I'm looking for the sum of all prime numbers under 2,000,000.

这是我...

int main(int argc, char *argv[]) { unsigned long int sum = 0; for (unsigned long int i = 0; i < 2000000; i++) { if (isPrime(i)) { sum += i; } } printf("sum => %lu\n", sum); } int isPrime(int num) { if (num < 2) { return 0; } for (int i = 2; i < num; ++i) { if (num % i == 0) { return 0; } } return 1; }

这需要年龄运行,因此它不会满足运行时的一分钟规则的欧拉的问题。

当我以10的极限运行它,它得到正确的答案, 17 像的问题。

When I run it with the limit of 10, it gets the correct answer, 17 like in the question.

我的猜测是有一定的算法,可以减少工作正在做。问题是,我不知道它是什么。

My guess is there is some algorithm that can reduce the work being done. Problem is, I don't know what it is.

可有人请点我朝着正确的方向?

Can someone please point me in the right direction?

感谢。

推荐答案

通过 I 从 2 到 2000000 (或任何上限),一旦你确定 I 为素数,你后来才知道, {2I,3I,4I,...,NI} 不是素数,其中 NI&LT; = 2000000 。

With i from 2 to 2000000 (or whatever upper limit), once you determine that i is prime, you then know that {2i, 3i, 4i, ..., ni} are not prime numbers, where ni <= 2000000.

您不必测试这些数字 - 你知道他们是不是素数

You don't need to test those numbers — you know they aren't prime.

当你通过你的 testNumbers 阵列进步和消除这个列表的数字,数字,你知道现在是不是素数,则显著减少你真正需要测试的数字

As you progress through your array of testNumbers and eliminate numbers from this list, numbers that you now know are not prime, you significantly reduce the numbers you actually need to test.

是的,这是埃拉托色尼的筛。

Yes, this is the Sieve of Eratosthenes.

更多推荐

需要帮助优化算法

本文发布于:2023-11-29 23:02:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647893.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:算法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!