用另一种方法将两个整数相除

用另一种方法将两个整数相除

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

问题描述

让我们考虑 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.

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

08-24 08:34