Processing math: 100%

Lesson goal: Add fractions using Prolog

Previous: Counting in Prolog | Home | Next: Divisibility rules

Let's write some Prolog that will add fractions together. This takes a bit of logic, as you may remember from your math class.

Suppose you have two fractions N1/D1 and N2/D2, where N means numerator and D means denominator. The 1 and 2 refer to fractions 1 and 2 to add together, so we'd like to find N1/D1+N2/D2.

You probably remember the plan:
  • If the denominators are the same, or D1=D2, then the sum will have this denominator, with the two numerators added together. This means Nsum=N1+N1 and Dsum=D1 (or D2). The answer will be Nsum/Dsum.

  • If the denominators are different, or D1D2, we'll have to find a common denominator Dsum, which is Dsum=D1×D2. The numerator of fraction 1 will become N1=N1×D2, and the numerator of fraction 2 will become N2=N2×D1. Now, the numerator of the sum will be the sum of the new numerators, or Nsum=N1+N2. Once again, the answer will be Nsum/Dsum.
As an example, if the denominators are the same, as in 1/5+2/5. The answer will be 3/5. If the demoninators are different, like 2/3+1/4, the 2/3 will become 8/12 and the 1/4 will become 3/12. The answer will be 8/12+3/12=11/12.

As for Prolog, we'd like the goal to be something like add(1,5,2,5,Nsum,Dsum). for which we'd like Prolog to find Nsum to be 3 and Dsum to be 5. For something like add(2,3,1,4,Nsum,Dsum)., we'd like Prolog to find Nsum to be 11 and Dsum to be 12.
add(N1,D,N2,D,Nsum,D):- Nsum is N1 + N2.
add(N1,D1,N2,D2,Nsum,Dsum)
Move the mouse over a dotted box for more information.

Now you try. Finish the code for the fractions with different denominators.

Type your code here:

10
 
1
add(N1,D,N2,D,Nsum,D) :- Nsum is N1 + N2.
2
3
add(N1,D1,N2,D2,Nsum,Dsum) :- 
4
                        D1 ?? D2, 
5
                        Dsum is ??,
6
                        N1p is ??,
7
                        N2p is ??,
8
                        Nsum is ??.
9
10
goal: add(2,5,3,10,A,B).

See your results here: