素数程序 [英] Prime number program

查看:110
本文介绍了素数程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我该如何编写一个程序来查找并打印3-100之间的所有素数?

How do I write a program that finds and prints all of the prime numbers between 3-100?

推荐答案

请尝试以下代码示例:

Try this code sample:

#include
using namespace std;
void prime_num(int);
int main()
{
    cout << " Enter a number and I will generate the prime numbers up to that number: ";
    int num = 0;
    cin >> num;
    prime_num(num);
}

void prime_num( int num)
{
    bool isPrime=true;
    for ( int i = 0; i <= num; i++)
    {
        for ( int j = 2; j <= num; j++)
        {
            if ( i!=j && i % j == 0 )
            {
                isPrime=false;
                break;
            }
        }
       if (isPrime)
       {
           cout <<"Prime:"<< i << endl;
       }
       isPrime=true;
    }
}


您应该可以解决此问题,只需将其分解成较小的块即可

1)构造您的for循环-别忘了您可以增加2倍
2)写出打印声明
3)参见除数规则 [ ^ ],以查看规则是否包含任何简单因素
4)检查当前数字是否可以除以到目前为止发现的素数

这应该足以让您入门
You should be able to work this out, just break it down into smaller chunks

1) construct your for loop - don''t forget you can increment by a factor of two
2) write print statement
3) See Divisibility rule[^] for the rules to see if a number has any simple factors
4) Check to see if the current number can be divided by any of the discovered primes so far

This should be enough to get you started


Eratosthenes的筛子 [ ^ ]一直是我的最爱:).
Fermat Primality测试 [原始性测试 [^ ]

最好的问候,

—MRB
The Sieve of Eratosthenes[^] was always a favorite of mine :).
Another oldy but goodie is the Fermat Primality Test[^]. Since the Fermat Primality Test does have its flaws you might want to resort to this page, which lists other primality tests: Primality Test[^]

Best Regards,

—MRB


这篇关于素数程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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