4

I am a novice in prolog programming, i use swi-prolog. Now I'm stucked by some math problems

as we know the predicate :A is 3+3.works well,the answer is A=6.

but if I want to find two digits (A and B) from 0~9 that a+b=6 6 is A+B does't work. so I want to know if there is a easy way to do this? And what if I want to find 3 digits (A,B and C)from 0~9 that A+B+C=13 how to do this ?

repeat
  • 18,496
  • 4
  • 54
  • 166
Lin Jiayin
  • 499
  • 1
  • 6
  • 11

3 Answers3

2

the simpler way, working in every Prolog implementation: declare a predicate digit/1 (the notation predicate/N means that predicate has N arguments)

digit(D) :- member(D, [0,1,2,3,4,5,6,7,8,9]).

then you can ask

?- digit(A),digit(B),6 is A+B.
A = 0,
B = 6 ;
A = 1,
B = 5 ;
...

since sum is symmetric, maybe you want to reduce the duplicate solution with

?- digit(A),digit(B),A=<B,6 is A+B.

Using library(clpfd) you can avoid defining your digit/1 predicate, and gain a lot of functionality:

?- [library(clpfd)].
true.

?- [A,B,C] ins 0..9, A+B+C #= 13, label([A,B,C]).
A = 0,
B = 4,
C = 9 ;
A = 0,
B = 5,
C = 8 
...

note that now the incognite can stay to the left of the 'assignment'...

CapelliC
  • 59,646
  • 5
  • 47
  • 90
2

My advice to you as a Prolog novice is this:

  1. First things first!

  2. Use clpfd! You can start right now by reading the tag information section on tag .

  3. Pick up the habit of starting new file with extension .pl with the following line:

    :- use_module(library(clpfd)).
  4. Use clpfd everytime you want to express Prolog relations over integers: Every. Single. Time.

  5. Witness that clpfd is already widely available and that it is still gaining ground.

  6. Realize that you will profit the most if you learn first—not 1970's style (is)/2!

    Why? (is)/2 is a low-level feature best used by constraint solver implementors.

false
  • 10,264
  • 13
  • 101
  • 209
repeat
  • 18,496
  • 4
  • 54
  • 166
1

Doing math with prolog is interesting. This looks like an assignment and I would not like to solve it, but I will try to help you find the answer yourself. Given the restricted range of your problem you could probably define every integer from 0 to 9 by creating a simple prolog programm. Keep in mind that you can define also functions like:

add3(A, B, C,SUM) :- SUM is A + B + C.

You could try to solve the problem by an Equation Solver. See this answer: Equation solver in SWI-Prolog

Or using Constraint Logic Programming. http://www.swi-prolog.org/man/clpqr.html

Community
  • 1
  • 1
Spyros K
  • 2,480
  • 1
  • 20
  • 37