素数C ++程序

时间:2013-07-02 17:34:07

标签: c++ primes

我不确定我是否应该问这里或程序员,但我一直在努力弄清楚为什么这个程序不会工作,虽然我发现了一些错误,但它仍然会返回“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 ++(以及一般的编程)非常陌生。

这只是为了对功能和控制进行测试。

7 个答案:

答案 0 :(得分:5)

i永远不能等于a - 1 - 你只能达到b - 1ba/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;即可。

答案 1 :(得分:1)

你的逻辑错误。你正在使用这个表达式(i == a -1)),这个表达式永远不会像卡尔所说的那样真实。

例如: -

 If a = 11

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

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

答案 2 :(得分:1)

你可以通过检查直到平方根来做到这一点。但下面是对您的代码进行一些修改以使其工作。

#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;

}

答案 3 :(得分: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;

        }
 }
}
}

答案 4 :(得分:0)

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();
    }
}

答案 5 :(得分:0)

以下是查找Prime数字的完整解决方案,直到任何用户输入数字。

#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();
}

答案 6 :(得分:0)

一种方法是使用Sieving算法,例如sieve of 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));
}