用另一种方法除以两个整数 [英] Dividing two integers with an alternative way

查看:92
本文介绍了用另一种方法除以两个整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们考虑n = s(s(... s(0)...))(仅n = s ^ n(0)).如何编写一个程序来计算两个整数的除法?我的意思是s ^(n//m)(即除法的定义).有任何想法吗?例如,如果我们有问题:

Let's consider that n=s(s(...s(0)...)) (simply n= s^n(0)). How could write a program calculating the division of two integers? I mean s^(n//m) (thats the definition of the division) . Any ideas? For example, if we had the question:

?-divide(s(s(s(s(0)))),s(0),D). 

我写了以下代码:

 nat(0).
 nat(s(X)) :- nat(X).
 divide(0,_,D) :- D is 0.
 divide(s(X),s(Y),D) :- divide(X,Y,D). 

推荐答案

您的谓词divide/3错误地假定当x和y为数字时,以下等式成立: (x-1)/(y-1)= x/y
一个反例是:(16-1)/(4-1)= 5 16/4 = 4

Your predicate divide/3 assumes wrongly that the following equation holds when x and y are numbers: (x-1)/(y-1) = x/y
A counter-example is: (16-1)/(4-1) = 5 is different from 16/4 = 4

您似乎正在尝试将谓词基于众所周知的加法谓词:

It seems you are trying to base your predicate on the well-know addition predicate:

add(0,Y,Y).
add(s(X),Y,s(Z)) :- add(X,Y,Z).

但是除法是乘法而不是加法运算.解决问题的一种可能方法是将除法视为迭代减法(因为乘法是迭代加法).由于您的谓词基于自然数,因此必须按照您在问题中所写的那样执行整数除法.

but division is a multiplicative not an additive operation. A possible way of solving your problem is to think of division as an iterated subtraction (as multiplication is an iterated addition). As your predicate is on natural numbers it must implement integral division as you wrote in the question.

这篇关于用另一种方法除以两个整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆