0

I was making this program to find the reverse factorial of give number in prolog, but its not working it is returning false everytime. Here is the code.

fr(X,Y):-fr(X,2,Y).

fr(X,P,Y):- X =< 1,Y is P-1.
fr(X,Q,Y):-D is X/Q,
      H is X mod Q,
      H =:= 0,
      Q1 is Q+1,
      fr(D,Q1,Y).

Here is who this code is supposed to work , it takes 2 argument like this (24,Who). from two argument function I call a 3 argument function ,Which is basically check if the given number is divided by 2 and if it is then it increment in Q and check if the number is divided by 3 and so on.

affan
  • 1
  • 1
  • 3
  • 1
    `Q is Q + 1` will always fail because you cannot reassign a variable's value. Use `Q1 is Q + 1, fr(D, Q1, Y)` instead. – lurker Mar 01 '15 at 18:14
  • 1
    Now that the Q is fixed try to solve it. If I thought that was the only problem I would have posted it as an answer rather than a comment. If you're still stuck, then update your question (edit) with the updates code and new, unexpected results. – lurker Mar 01 '15 at 18:21
  • its Working, the problem is that i was trying to take mod of D instead of 'code' H is X mod Q 'code', – affan Mar 01 '15 at 18:25
  • The code in the post is working fine , thanks @lurker – affan Mar 01 '15 at 18:27
  • I'm glad you got it sorted :) – lurker Mar 01 '15 at 18:56
  • 1
    By the way, you can skip the `H` and just write, `0 =:= X mod Q` and the division, technically, should be integer division: `D is X // Q`, although the check for zero remainder will make it functionally not matter. The integer division keeps `D` an integer. Otherwise, `D` will be a float. – lurker Mar 01 '15 at 20:18

1 Answers1

1

First, take a step back and leave your old code behind. Then proceed like this:

  1. Use instead of plain-old Prolog arithmetic predicates like is/2 and friends!

  2. Focus on the "relational" side of problem solving.

    Look at this very related question and the fine answers proposed there.

  3. Beware of premature optimization!

    Once you do know the ins-and-outs of some domain, don't shy away from optimization, either: it can be great fun and there's a lot to learn, too! (Mind the law of diminishing returns, though.)

Community
  • 1
  • 1
repeat
  • 18,496
  • 4
  • 54
  • 166