A perfect number is one that is equal to the sum of all its divisors excluding itself. e.g. 6 = 1+2+3, then 6 is a perfect number.
I am wondering how to implement this in PROLOG.
Can you give me some ideas?
A perfect number is one that is equal to the sum of all its divisors excluding itself. e.g. 6 = 1+2+3, then 6 is a perfect number.
I am wondering how to implement this in PROLOG.
Can you give me some ideas?
-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.