以下作業題,請各位幫忙指點,因剛學c++,請各位老師在程序盡量多些注釋說明。謝謝!正整數n是素數,如果它只能由1和本身整除。(1)寫一個名為ISPrime的C++函數,它取正整數參數,如果參數為Prime,則返回true,否則返回false。假設參數大于1(2)寫一個C++函數,名為SUFFPrimes,取正整數參數n,并返回第一N素數的和。例如,SUFFPrimes(6)必須返回41,這是前6個素數的總和:2+3+5+7+11+13=41。您必須使用在部分(1)中定義的ISPrime函數來定義函數SUFFPROMES。原題:A positive integer number n is prime if it is divisible by ONLY 1 anditself.a. Write a C++ function named isPrime that takes a positiveinteger argument and returns true if the argument is prime and returnsfalse otherwis。 Assume the argument is greater than 1. b.Write a C++ function named sumOfPrimes that takes a positive integerargument n and returns the sum of the first n prime numbers. For example,sumOfPrimes(6) must return 41 , which is the sum of the first 6 prime numbers:2+3+5+7+11+13 = 41. You must use the isPrime function you defined in part (a) to define the function sumOfPrimes.
1 回答
哈士奇WWW
TA貢獻1799條經驗 獲得超6個贊
第一題
#include <stdio.h>
#include <iostream>
using namespace std;
bool ISPrime(const int & num)
{
if(num <=1)
{
return false;
}
int i = 2;
//素數就是指 因子只有自己和1
//i 從二開始
//用num除以i,若是可以除盡,且i小于num 就說明num 存在別的因子
//所以num就不是素數
for(i = 2; i < num; ++i)
{
if(num % i == 0)
{
break;
//若可以除盡,就跳出循環
}
}
if(i == num)
{
return true;
//如果出循環且i值已經等于num
//說明是素數
}
return false;
//否則不是素數
}
int main()
{
int n = 19;
bool ret = ISPrime(n);
if(ret)
{
printf("Is Prime\n");
}
else
{
printf("Not Prime\n");
}
return 0;
}第二題
#include <stdio.h>
#include <iostream>
using namespace std;
int SUFFPrime(const int & n)
{
int sum = 0;
if(n <= 0)
{
return sum;
}
int i = 2;
int count = 0;
int num = 2;
//素數就是指 因子只有自己和1
//i 從二開始
//用num除以i,若是可以除盡,且i小于num 就說明num 存在別的因子
//所以num就不是素數
//外層循環用來控制個數,個數應該小于 n
//內層循環用來判斷當前數字是不是素數
while(count < n)
{
for(i = 2;i < num ; ++i)
{
if(num % i == 0)
{
break;
//若可以除盡,就跳出循環
}
}
if(i == num)
{
//如果出循環且i值已經等于num
//說明是素數
count++;
sum += num;
}
//否則不是素數
//就看下一個數是不是素數
num++;
}
return sum;
}
int main()
{
int n = 7;
int sum = SUFFPrime(n);
printf("sum: %d\n",sum);
return 0;
}- 1 回答
- 0 關注
- 775 瀏覽
添加回答
舉報
0/150
提交
取消
