習題6-3 使用函數(shù)輸出指定范圍內(nèi)的完數(shù) (20 分)
1. 題目摘自
https://pintia.cn/problem-sets/12/problems/310
2. 題目內(nèi)容
本題要求實現(xiàn)一個計算整數(shù)因子和的簡單函數(shù)淘衙,并利用其實現(xiàn)另一個函數(shù),輸出兩正整數(shù) m
和 n(0<m≤n≤10000)
之間的所有完數(shù)。所謂完數(shù)就是該數(shù)恰好等于除自身外的因子之和。例如:6=1+2+3
,其中 1周崭、2、3
為 6
的因子。
函數(shù)接口定義:
int factorsum( int number );
void PrintPN( int m, int n );
其中函數(shù) factorsum
須返回 int number
的因子和答朋;函數(shù) PrintPN
要逐行輸出給定范圍 [m, n]
內(nèi)每個完數(shù)的因子累加形式的分解式,每個完數(shù)占一行棠笑,格式為“完數(shù) = 因子 1
+ 因子 2
+ ... + 因子 k
”梦碗,其中完數(shù)和因子均按遞增順序給出。如果給定區(qū)間內(nèi)沒有完數(shù)蓖救,則輸出一行 No perfect number
洪规。
輸入樣例1:
1 30
輸出樣例1:
1 is a perfect number
1 = 1
6 = 1 + 2 + 3
28 = 1 + 2 + 4 + 7 + 14
輸入樣例2:
7 25
輸出樣例2:
No perfect number
3. 源碼參考
#include<iostream>
using namespace std;
int factorsum(int number);
void PrintPN(int m, int n);
int main()
{
int i, m, n;
cin >> m >> n;
if (factorsum(m) == m)
{
cout << m << " is a perfect number" << endl;
}
if (factorsum(n) == n)
{
cout << m << " is a perfect number" << endl;
}
PrintPN(m, n);
return 0;
}
int factorsum(int number)
{
if (number == 1)
{
return 1;
}
int n = number / 2;
int s = 0;
for (int i = 1; i <= n; i++)
{
if (number % i == 0)
{
s += i;
}
}
return s;
}
void PrintPN(int m, int n)
{
int cnt = 0;
for (int i = m; i <= n; i++)
{
if (factorsum(i) == i)
{
cnt++;
cout << i << " = 1";
for (int j = 2; j <= i / 2; j++)
{
if (i % j == 0)
{
cout << " + " << j;
}
}
cout << endl;
}
}
if (cnt == 0)
{
cout << "No perfect number" << endl;
}
return;
}