Trying to figure out how to write a recursive predicate divide_by(X, D, I, R) that takes as input a positive integer X and a divisor D, and returns the answer as the whole number part I and the remainder part R, however, I can't seem to get my head around Prolog. How would I go about doing this?
相关问题
- Do the Java Integer and Double objects have unnece
- Creating a SPARQL parameterized query using append
- How to join rules and print out outputs in prolog
- Splitting list and iterating in prolog
- Is it possible to distinguish Bool and Int in Swif
相关文章
- What are the problems associated to Best First Sea
- How can I fix this circular predicate in Prolog?
- How to negate in Prolog
- Remove incorrect subsequent solutions without once
- Lua Integer type
- How to use Int64 in C#
- More efficient way to get integer permutations?
- How to convert strings with billion or million abb
There are predefined evaluable functors for this.
(div)/2
and(mod)/2
always rounding down. Recommended by LIA-1, Knuth etc.(//)/2
and(rem)/2
rounding toward zero (actually, it's implementation defined, but all current implementations do it like that). You can ask this viacurrent_prolog_flag(integer_rounding_function, F)
which gives in current implementationstoward_zero
.The difference between those pairs shows only when negative numbers are involved. It is kind of a religious war which one to prefer. ISO/IEC 10967:2012 Language independent arithmetic (vl. LIA-1) only provides rounding down "due to proneness for erroneous use" (C.5.1.2.2) of toward_zero, whereas Fortran and followers like C go for toward_zero calling it "algebraic" (6.5.5). See also: Advantages of using truncation towards minus infinity vs towards zero
I'm assuming your teacher is trying to teach recursion.
Division is repeated subtraction, just as multiplication is repeated addition, n'est-ce-pas?
A common prolog idiom, since variables can only be assigned a value once, is to have an outer "public" predicate, that invokes a private "worker" predicate that uses the accumulator(s) and does the actual work. This leads us to a solution like this.
From this it should be pretty easy to modify the outer public predicate to account for signed operands, bearing in mind that
+/+
yields+
+/-
yields-
-/+
yields-
-/-
yields+
And that having evaluated
M/N
to obtain quotientQ
and remainderR
, the propertyholds true. That should inform you as to the required signs for the quotient and remainder. Don't forget that addition of a negative number is the same as subtraction:
M + -N
is equivalent toM - N
. That will get you to results that are mathematically correct (which may differ from the results obtained via your computer's integer division instructions). One should note that for the property noted above to be true, the sign of the quotient and the sign of the remainder may differ.If you had to limit your arithmetic operations to addition, subtraction, then you could use recursion as follows: