繁体   English   中英

素数C ++程序

[英]Prime number C++ program

我不确定是否应该在这里询问程序员,还是我应该问程序员,但是我一直在试图弄清为什么该程序无法运行,尽管我发现了一些错误,但即使返回x也不是素数。

#include <iostream>
using namespace std;


  bool primetest(int a) {
 int i;
 //Halve the user input to find where to stop dividing to (it will remove decimal point as it is an integer)
 int b = a / 2;
 //Loop through, for each division to test if it has a factor (it starts at 2, as 1 will always divide)
 for (i = 2; i < b; i++) {
     //If  the user input has no remainder then it cannot be a prime and the loop can stop (break)
     if (a % i == 0) {
           return(0);
           break;
     }
     //Other wise if the user input does have a remainder and is the last of the loop, return true (it is a prime)
              else if ((a % i != 0) && (i == a -1)) {
          return (1);
          break;
     }
 }   
}

 int main(void) {
int user;
cout << "Enter a number to test if it is a prime or not: ";
cin >> user;
if (primetest(user)) {
                   cout << user << " is a prime number.";
}
else  {
      cout << user<< " is not a prime number.";
}
cout << "\n\nPress enter to exit...";
getchar();
getchar();
return 0;
}

抱歉,如果它太本地化(在这种情况下,您可以建议我在哪里问这样的具体问题?)

我应该补充一点,我对C ++(和一般的编程)非常陌生

这仅仅是为了测试功能和控件。

i永远不会等于a - 1你只会上升到b - 1 ba/2 ,永远不会导致匹配。

这意味着将返回1的循环结束条件永远不会成立。

如果是质数,则循环结束。 这会导致不确定的行为,因为那里没有return语句。 Clang发出了警告,没有任何特殊标志:

example.cpp:22:1: warning: control may reach end of non-void function
      [-Wreturn-type]
}
^
1 warning generated.

如果您的编译器没有警告您,则需要打开更多警告标志。 例如,添加-Wall会在使用GCC时发出警告:

example.cpp: In function ‘bool primetest(int)’:
example.cpp:22: warning: control reaches end of non-void function

总体而言,素数检查循环要复杂得多。 假设你只关心的值a大于或等于2

bool primetest(int a)
{
    int b = sqrt(a); // only need to test up to the square root of the input

    for (int i = 2; i <= b; i++)
    {
        if (a % i == 0)
           return false;
   }

   // if the loop completed, a is prime
   return true;
}

如果要处理所有int值,则可以添加if (a < 2) return false; 一开始。

您的逻辑不正确。 您正在使用此表达式(i == a -1)) ,就像卡尔所说的那样,它永远不可能是正确的。

例如:-

 If a = 11

 b = a/2 = 5  (Fractional part truncated)

因此,您正在循环运行直到i<5 所以i永远不能等于a-1因为在这种情况下i的最大值将是4而a-1值将是10

您只需检查直到平方根即可。 但是下面是对代码的一些修改,以使其正常工作。

#include <iostream>
using namespace std;
bool primetest(int a) {
int i;
//Halve the user input to find where to stop dividing to (it will remove decimal point as it is an integer)
int b = a / 2;
//Loop through, for each division to test if it has a factor (it starts at 2, as 1 will always divide)
for (i = 2; i <= b; i++) {
 //If  the user input has no remainder then it cannot be a prime and the loop can stop (break)
 if (a % i == 0) {
       return(0);

 }
}
//this return invokes only when it doesn't has factor
return 1;   
}

int main(void) {
  int user;
  cout << "Enter a number to test if it is a prime or not: ";
  cin >> user;
  if (primetest(user)) {
               cout << user << " is a prime number.";
  }
  else  {
     cout << user<< " is not a prime number.";
  }

return 0;

}

看一下这个:

//Prime Numbers generation in C++
//Using for loops and conditional structures
#include <iostream>
using namespace std;

int main()
{
int a = 2;       //start from 2
long long int b = 1000;     //ends at 1000

for (int i = a; i <= b; i++)
{

 for (int j = 2; j <= i; j++)
 {
    if (!(i%j)&&(i!=j))    //Condition for not prime
        {
            break;
        }

    if (j==i)             //condition for Prime Numbers
        {
              cout << i << endl;

        }
 }
}
}
main()
{
    int i,j,x,box;
    for (i=10;i<=99;i++)
    {
        box=0;
        x=i/2;
        for (j=2;j<=x;j++)
            if (i%j==0) box++;
        if (box==0) cout<<i<<" is a prime number";
        else cout<<i<<" is a composite number";
        cout<<"\n";
        getch();
    }
}

这是查找素数直到所有用户输入的数字的完整解决方案。

#include <iostream.h>
#include <conio.h>
using namespace std;

main() 
{
 int num, i, countFactors;
 int a;
 cout << "Enter number " << endl;
 cin >> a;

 for (num = 1; num <= a; num++)
 {
  countFactors = 0;
  for (i = 2; i <= num; i++)
  {
   //if a factor exists from 2 up to the number, count Factors
   if (num % i == 0)
   {
    countFactors++;    
   }
  }

  //a prime number has only itself as a factor
  if (countFactors == 1)
  {
   cout << num << ", ";
  }
 }

 getch();
}

一种方法是使用筛选算法,例如Eratosthenes筛选器 这是一种非常有效的快速方法。

bool isPrime(int number){
  if(number == 2 || number == 3 | number == 5 || number == 7) return true;
  return ((number % 2) && (number % 3) && (number % 5) && (number % 7));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM