2

完美数等于除自身之外的所有除数之和。例如 6 = 1+2+3,那么 6 是一个完美数。

我想知道如何在 PROLOG 中实现这一点。

你能给我一些想法吗?

4

1 回答 1

0

-Hello Steven,as you may be aware by now PROLOG is a declarative language where we express the program logic using relations.

Your task is to express the relation between a given number and the sum of its divisors. In order to find the sum, you will have to iterate through all possible integers starting from 1 to Number-1(since Number wont be included in the sum) and test whether a given integer is a divisor of the input number. If the integer is a divisor then add it to the current sum,increment the integer and repeat the task until you reach an integer that has the same value as the input number. Once you get there all you have to do is check the sum( if the sum is equal to our input number, we have a perfect number,otherwise we don't). Below are given the predicates we need :

perfectNumber(Number) :- perfectNumber(Number,1,0).

perfectNumber(Number,Number,Sum):- Number = Sum.
perfectNumber(Number,CurrDivisor,CurrSum) :-  not(CurrDivisor = Number),
                                              NewDivisor is CurrDivisor+1,
                                              0 is mod(Number,CurrDivisor), 
                                              NewSum is CurrSum+CurrDivisor,
                                              perfectNumber(Number,NewDivisor,NewSum).

perfectNumber(Number,CurrDivisor,CurrSum) :- not(CurrDivisor = Number),
                                             NewDivisor is CurrDivisor+1,perfectNumber(Number,NewDivisor,CurrSum).

Let me know what you think.

于 2012-12-03T19:51:29.663 回答