我正在尝试实现一个从用户读取正整数的程序,并输出2和userNum
之间的所有完美数字。它还输出介于2和userNum
之间的所有友好数字对。两个数字都必须在范围内。我正在为此努力奋斗。
要求:
1)对AnalyzeDivisors
的调用必须一起保持到theta(userNum)次。 2)函数void AnalyzeDivisors
必须采用以下参数int num, int& outCountDivs, int& outSumDivs
。 3)函数bool IsPerfect
必须采用以下参数int num
。
老实说,我不知道如何在这个效率范围内做到这一点。我现在能够通过将规则弯曲到IsPerfect函数的参数来确定范围内的所有完美数字,但是如何在不调用Analyze Dividors的情况下确定友好对,并且每次迭代主循环中的for循环?
任何帮助将不胜感激!代码如下:
主要
int main()
{
int userNum;
//Request number input from the user
cout << "Please input a positive integer num (>= 2): " << endl;
cin >> userNum;
for (int counter = 2; counter <= userNum; counter++)
{
//Set variables
int outCountDivs = 0, outSumDivs = 0, otherAmicablePair = 0;
bool perfectNum = false, isAmicablePair = false;
//Analyze dividors
AnalyzeDividors(counter, outCountDivs, outSumDivs);
//determine perfect num
perfectNum = IsPerfect(counter, outSumDivs);
if (perfectNum)
cout << endl << counter << IS_PERFECT_NUM;
}
return 0;
}
AnalyzeDividors
void AnalyzeDividors(int num, int& outCountDivs, int& outSumDivs)
{
int divisorCounter;
for (divisorCounter = 1; divisorCounter <= sqrt(num); divisorCounter++)
{
if (num % divisorCounter == 0 && num / divisorCounter != divisorCounter && num / divisorCounter != num)
{
//both counter and num/divisorCounter
outSumDivs += divisorCounter + (num / divisorCounter);
outCountDivs += 2;
}
else if ((num % divisorCounter == 0 && num / divisorCounter == divisorCounter) || num/divisorCounter == num)
{
//Just divisorCounter
outSumDivs += divisorCounter;
outCountDivs += 1;
}
}
}
IsPerfect
bool IsPerfect(int userNum, int outSumDivs)
{
if (userNum == outSumDivs)
return true;
else
return false;
}