C ++如何用eratosthenes筛子生成素数? [英] C++ how do I generate prime numbers with sieve of eratosthenes?

查看:81
本文介绍了C ++如何用eratosthenes筛子生成素数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要生成高达150的素数。

这是我到目前为止所拥有的。从这里应该改变什么?



我尝试过:



I need to generate prime numbers up to 150.
This is what I have so far. What should be changed from here?

What I have tried:

int main(void)
{
	int p=2, prime[150], i,n;

	for (p = 2; p <= 150; ++p){
		for (i = 2; i <= 150; ++i){
			n = p*i;
			prime[i] = i;
			prime[n] = 1;	
		}
	}
	printf("%i\n", prime[i]);

	return 0;
}

推荐答案

您应该学习尽快使用调试器。而不是猜测你的代码在做什么,现在是时候看到你的代码执行并确保它完成你期望的。



调试器允许你跟踪执行逐行检查变量,你会看到它有一个停止做你期望的点。

调试器 - 维基百科,免费的百科全书 [ ^ ]

掌握Visual Studio 2010中的调试 - A初学者指南 [ ^ ]



调试器在这里向您展示您的代码正在做什么,您的任务是与它应该做什么进行比较。 />
当代码不做ex的时候你接近一个错误。



建议:拿一张纸并尝试手工完成,你的程序应该使用相同的程序。 />
问自己一些问题:

- 我怎么知道实际的数字是素数?

- 当我得到一个新的素数时,什么是否尚未检查为非素数的素数的第一个倍数的值?
You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.

The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.
Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]

The debugger is here to show you what your code is doing and your task is to compare with what it should do.
When the code don't do what is expected, you are close to a bug.

Advice: take a sheet of paper and try to do it by hand, your program should use the same procedure.
Ask your self a few questions:
- How do I know that actual number is a prime ?
- When I got a new prime, What is the value of the first multiple of that prime that is not already checked as non prime ?


如果要实现此类算法,则必须先了解它。为了理解它,一个很好的阅读是它的维基百科页面: Sierat of Eratosthenes - 维基百科,免费的百科全书 [< a href =https://en.wikipedia.org/wiki/Sieve_of_Eratosthenestarget =_ blanktitle =New Window> ^ ]。
If you want to implement such algorithm then you have to first understand it. In order to understand it, a good reading is its very wikipedia page: Sieve of Eratosthenes - Wikipedia, the free encyclopedia[^].


这篇关于C ++如何用eratosthenes筛子生成素数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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