-7

抱歉,我的电子课程作业有问题。我被要求编写一个程序来确定用户输入的数字是否是素数,然后说出它的素数,或者给出输入可被整除的数字。我应该使用哪种语法来实现它?
例如:“6 可与 6;3;2;1 整除”这是我目前的代码:

   #include<iostream>
   #include<conio.h>  
   using namespace std;
   int main()  
   {
   int P,count=0;
   cout<<"Enter a number:\n"; /*Asks for user input*/
   cin>>P;                    /* User input P*/
   for(int a=1;a<=P;a++)
   {
   if(P%a==0)
   {
   count++;
   }
   if(count==2)
         {
        cout<<"Prime number.\n";  /* Provided option when the number is prime number*/
         }
       else
        {
          cout<<" Not prime number \n"; /* This is where I am supposed to provide the               numbers input is divisible with*/
        }
   getch();
   } 
   }
4

1 回答 1

2

不完全确定出了什么问题,但是您的程序会打印出类似

Enter a number:
6
 Not prime number 
Prime number.
 Not prime number 
 Not prime number 
 Not prime number 
 Not prime number

此外,<conio.h>不是标准的 C++。我建议你写这样的东西(注意使用std::vector来累积除数):

#include <iostream>
#include <vector>

int main()
{
    int n;
    std::cout << "Enter a number: ";
    std::cin >> n;

    if (n == 0) {
        "Not a prime; 0 is divisible by all integers";
        return 0;
    }

    std::vector<int> divisors;

    for (int i = 1; i <= n; i++) {
        if (n % i == 0) {
            divisors.push_back(i);
        }
    }

    if (divisors.size() > 2) {
        std::cout << "Not a prime; divisors:" << std::endl;
        for (std::vector<int>::iterator it = divisors.begin(); it != divisors.end(); it++) {
            std::cout << *it << std::endl;
        }
    } else {
        std::cout << "Prime" << std::endl;
    }

    return 0;
}
于 2013-02-24T20:14:39.643 回答