1

So I'm trying to work out in Prolog how to take an input, and return whether it is a perfect number or not. Currently i'm close but can't figure out why it isn't working the way I want. I am approaching this through recursion. If X %N == 0, then N and TT(total) is added to TT1. N will decrease by one and the function will be called recursively until it reaches 1, then the total will be compared to the input number X. My code is:

factors(X,N,TT) :-
   (  0 is X mod N -> TT1 is N + TT ),
   TT = TT1,
   (  N > 1 ->  N1 is N-1, factors(X, N1, TT1)
   ;  TT1 = X
   ).

perfect(X) :-
    factors(X, X-1, 0).

Currently it is returning that all inputs are false. I hope this isn't majorly incorrect and only needs to be tweaked.

Cheers

false
  • 10,264
  • 13
  • 101
  • 209
Killian Byrne
  • 33
  • 1
  • 7
  • It looks like, in `factors/3`, `TT` is already bound (via the call). Then if you do compute `TT1 is N + TT` and then check for unification, `TT = TT1`, that unification fails since `TT` and `TT1` are likely bound to different values. Did you mean `TT = TT1` as an alternative to `TT1 is N + TT`? In which case your `->/2` expression and following unification check need "tweaking". – lurker Dec 11 '17 at 21:57
  • 2
    Is [your friend](https://stackoverflow.com/questions/47742914/prolog-perfect-number-generation) in the same class? [Maybe this one](https://stackoverflow.com/questions/47744880/cant-understand-prolog-line-of-code) too? – Daniel Lyons Dec 11 '17 at 22:30
  • 2
    @lurker: Prepare yourself, soon the Mjölnir will be yours. – false Dec 11 '17 at 22:31

1 Answers1

0

Here a solutions, hope it helps

factors(_,N,N,_).
factors(X,N,NT,Sum):-
    N < NT,
    (   0 is X mod N ->  
        Sum1 = Sum + N
    ; Sum1 = Sum),
    N1 is N + 1,
    factors(X,N1,NT,Sum1).

perfect(X):-
    XT is X/2 + 1,
    factors(X,1,XT,0).
damianodamiano
  • 2,528
  • 2
  • 13
  • 21