題目連結 http://zerojudge.tw/ShowProblem?problemid=c032。
此題用迴圈從判斷1到 N/2 是否為 N 的因數,若是則加總(s)。接著比較加總結果與 N的大小關係來輸出對應的訊息。(那有沒有更好的演算法呢?)
C++程式碼:
#include <iostream>
#include <iomanip>
using namespace std;
/*
15 28 6 56 60000 22 496 0
15 DEFICIENT
28 PERFECT
6 PERFECT
56 ABUNDANT
60000 ABUNDANT
22 DEFICIENT
496 PERFECT
*/
short checkPerfection(int n)
{
int sum = 0;
for( int i = 1; i <= n/2; i++ )
if( n % i == 0 )
sum += i;
if( n == sum )
return 0; // perfect
else if( n > sum )
return -1; // deficient
else if( n < sum )
return 1; // abundant
}
void prnMsg(short choice)
{
switch( choice )
{
case 0:
cout << "PERFECT";
break;
case 1:
cout << "ABUNDANT";
break;
case -1:
cout << "DEFICIENT";
break;
default:
break;
}
cout << endl;
}
int main()
{
int input[100];
int size = 0;
while( cin >> input[size] )
{
if( input[size] == 0 )
break;
size++;
}
cout << "PERFECTION OUTPUT" << endl;
for( int i = 0; i < size; i++ )
{
cout.width(5);
cout << input[i] << " ";
prnMsg(checkPerfection(input[i]));
}
cout << "END OF OUTPUT";
return 0;
}
Python程式碼:
import sys
msg = {0:"PERFECT", 1:"ABUNDANT", -1:"DEFICIENT"}
def checkPerfection(n):
sum = 0
for i in range(1, (n // 2) + 1, 1):
if( n % i == 0 ):
sum += i
if( n == sum ):
return 0
elif( n > sum ):
return -1
elif( n < sum ):
return 1
num = []
n = 1
for s in sys.stdin:
tn = list(map(int,s.split()))
for n in tn:
if n == 0:
break
num.append(n)
if n == 0:
break
print('PERFECTION OUTPUT')
for n in num:
ret = checkPerfection(n)
print("%5d %s" % (n, msg[ret]))
print('END OF OUTPUT')
沒有留言:
張貼留言