编写C/C ++程序以生成素数列表,并检查数字是否为素数 [英] Write a C/C++ program to generate prime number list and check whether a number is prime or not
问题描述
我可以编写"Eratosthenes筛"的代码,以生成直至n的所有素数.但是我想编写一个程序,该程序将生成所有素数(最多n个)并将其索引到数组中,而不是检查一个数是否为素数.有人可以帮我做吗?
例如:如果n = 10,则质数为2 3 57.将它们索引到数组a [] = {2,3,4,7}中.比编写程序并按数字作为键盘输入,然后检查数字是否为质数.我知道有一种简单的方法可以检查数字是否为质数,但是我想通过上述方式进行操作.我该怎么做?
I can write the code for "Sieve of Eratosthenes" to generate all the prime number up to n. But I want to write a program that will generate and index all the prime number (up to n) into an array, than check whether a number is prime or not. Can anyone please help me to do it?
For Example: if n = 10, than the prime number is 2 3 5 7. Index them into an array a[ ] = {2, 3, 4, 7}. Than write a program and press a number as input from keyboard, than check the number is prime or not. I know that there is a simple way to check whether a number is prime or not but I want to do it by the above way. How can I do that???
推荐答案
由于您将原始代码中的所有数字都标记为素数,因此,您应该已经有一个可以使用的查找表.
或者,您可以创建一个数组或使用简单的vector
[ ^ ]或list
[ C#中的Eratosthenes筛子 [
Since you mark all numbers in your original code as prime or not, you should already have a lookup table which you can use.
Alternatively you could create an array or use a simplevector
[^] orlist
[^] to store them. Then when the user enters a value you can look it up in the container and report accordingly.
Sieve of Eratosthenes in C#[^] is a sample article that should help.
这篇关于编写C/C ++程序以生成素数列表,并检查数字是否为素数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!