[英]C++ How to use a function returning a Boolean Value to determine prime numbers
I am suppose to make a program that asks a user to input an integer 'n' between 1 and 100, and have an input validation loop. 我假设制作一个程序,要求用户输入1到100之间的整数“ n”,并有一个输入验证循环。 The program will then calculate the first 'n' prime numbers and print them.
然后程序将计算第一个'n'质数并打印出来。 So I figured out how to calculate the prime numbers and display them, 10 numbers per line, all in the main function.
所以我想出了如何计算素数并在主要功能中每行显示10个素数。 What I have to do is to have a function called isPrime() that takes an integer and returns true if it is prime and false otherwise.
我要做的是拥有一个名为isPrime()的函数,该函数接受一个整数,如果为质数则返回true,否则返回false。 I'm not sure how to go about this.
我不确定该怎么做。 This is the code I have for function main().
这是函数main()的代码。
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int number;
int count = 0;
cout << "Enter an integer between 1 and 100: ";
cin >> number;
while (number < 0 || number > 100)
{
cout << "Invalid number." << endl;
cout << "Enter an integer between 1 and 100: ";
cin >> number;
}
cout << "The first " << number << " primes: \n" << endl;
for (int i = 2; number > 0; ++i)
{
bool isPrime = true;
for (int j = 2; j < i; ++j)
{
if (i % j == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
count++;
--number;
cout << setw(5) << i;
if (count % 10 == 0)
cout << endl;
}
}
cout << endl;
system("pause");
return 0;
}
Any help is good, thanks in advance. 任何帮助都很好,在此先感谢您。
You seem to be testing i % j for every j lower then i. 您似乎要在比i低的每个j处测试i%j。 But if you tested for j = 3 then you can exclude all multiples of 3. When a number can't be divided by 3 it can't be divided by 6. This will improve performance.
但是,如果您测试了j = 3,则可以排除3的所有倍数。如果数字不能被3除,则不能被6除。这将提高性能。
You can also implement the AKS primalty test https://en.wikipedia.org/wiki/AKS_primality_test This might be a little more work. 您还可以实施AKS素养测试https://en.wikipedia.org/wiki/AKS_primality_test可能需要更多工作。 I don't know the details of this test but it is deterministic and works on all numbers.
我不知道该测试的详细信息,但它是确定性的,并且适用于所有数字。
If you want a function bool isPrime(int number) you can just extract this code from your main method, it looks something like this: 如果您想要一个函数bool isPrime(int number),则可以从主方法中提取此代码,它看起来像这样:
bool isPrime(int number){
for (int j = 2; j < number/2; ++j)
{
if (number % j == 0)
{
return false;
}
}
return true;
}
The for loop in the main function will be something like: 主函数中的for循环将类似于:
for (int i = 2; number > 0; ++i)
{
if (isPrime(i))
{
count++;
--number;
cout << setw(5) << i;
if (count % 10 == 0)
cout << endl;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.