【问题标题】:find prime numbers up to n digits using only 1 loop statement [closed]仅使用 1 个循环语句查找最多 n 位的素数 [关闭]
【发布时间】:2021-08-21 00:00:01
【问题描述】:

我是编程新手并试图解决一些问题,在这个问题中,我试图仅使用 1 个循环语句来查找最多 n 位的素数。

【问题讨论】:

  • 记住2是唯一的偶素数,其他都是奇数。
  • @TimRoberts 我不认为这是不可能的,实际上我是编程新手,所以我只是想练习构建我的逻辑构建,这就是我尝试这个问题的原因,这不是一个作业。这只是一个逻辑构建问题。
  • 需要两个循环。您可以将一个循环隐藏为“递归”,也可以使用 Tapesh 将其中一个循环隐藏在另一个循环中的技巧,但这里仍然存在两个循环。

标签: c++ for-loop while-loop logic


【解决方案1】:

一个循环和递归:

#include <iostream>
#include <cmath>

#define NUDIGS 3 //number of digits

bool TestPrime(int n, int ndiv)
{
    if ( n == ndiv )
        return true;
    if ( (n % ndiv) == 0 )
        return false;
    return TestPrime (n, ++ndiv) ;
}

int main()
{
    //calculate the max number with BUDIGITS
    int max = pow(10, NUDIGS) - 1;
    std::cout << "testing numbers from 2 to " << max << std::endl;
    int ntot = 0;
    
    //Loop testing every number. '1' is not considered as a prime number.
    for (int i=2; i <= max; i++)
    {
         //call a recursive test
         if ( TestPrime(i, 2) )
         {
             std::cout << i << " is prime " << std::endl;
             ntot++;
         }
    }
    std::cout << ntot << " prime numbers found" << std::endl;
}

【讨论】:

  • 感谢您的帮助!我明白其中的逻辑。
【解决方案2】:
//this program will print prime number from 2 to N . and break loop 
without using break statment

#include <iostream>

using namespace std;
int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int range;
    cin>>range;
    int num=2;
    for(int i=2;i<=num;i++){
        if(num>range){
            i=num+1;
        }
        else{
            if(i==num){
                cout<<num<<" ";
                i=1;
                num=num+1;
            }
            else if(num%i==0){
                i=1;
                num=num+1;
            }
        }
    }
    cout<<endl;
    return 0;
}

【讨论】:

  • 感谢您的帮助。
  • 请不要建议在 Stack Overflow 上的回答中使用 #include &lt;bits/stdc++.h&gt;。请参阅:Why should I not #include <bits/stdc++.h>?。您应该编辑您的帖子以包含所需的 standard 标头,否则您可能会收到反对票。
  • @AdrianMole 哦,对不起……让我改一下……??
  • 为什么你从 2 开始并以 1 递增?这意味着您将浪费时间检查事件编号。您可以从 3 开始并以 2 递增来减少 50% 的时间。数字 2 是唯一的偶数。其他都是奇怪的。
  • 好吧好吧我明白了……你想说我应该做 num=3;然后 num=num+2;而且也没有偶数所以我应该做 i=3;并按 i=i+2 递增;我说的对吗?
猜你喜欢
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多