Prolog - 低于上限的数的倍数 [英] Prolog - Multiples of a Number Below an Upper Limit

查看:41
本文介绍了Prolog - 低于上限的数的倍数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在 Prolog 中制作一个程序,该程序将计算一个数字的所有倍数(包括其自身),不超过另一个数字的值.我正在使用以下查询进行测试:

I am currently making a program in Prolog that will calculate all of the multiples (including itself) of a number, that do not exceed the value of another number. I was testing with the query below:

    ?- multiples(4,12,R,0)

此查询将列出所有小于或等于 12 的 4 的倍数,例如.4, 8, 12. R 将返回结果,0 是我打算实现一个计数器的地方,该计数器将为每个乘法计数,例如.4*1,4*2,4*3.我被卡住了,我不确定简单地添加倍数并检查它是否低于上限或者是否可以使用计数器或累加器来完成是否是更好的设计.

This query would list all multiples of 4 that are less than or equal to 12 eg. 4, 8, 12. The R would return the result and 0 is where I was intending to implement a counter that would count up for each multiplication eg. 4*1,4*2,4*3. I am stuck and I am not sure if it would be a better design to simply add the multiples and check if it is below the upper bound or if it can be done with a counter or accumulator.

multiples(N,U,R,Ctr) :-
        N =< U,
        R is Ctr * N,
        R =< U,
        increment(Ctr,Ctr2),
        multiples(N,U,R,Ctr2).

increment(Num, Num1) :-
        Num1 is Num+1.

我相信我的程序在从自身内部调用倍数的递归步骤中失败了.我知道递归需要一个基本情况来允许它退出,但我完全被困在这里并且希望得到一些指导.

I believe my program is failing at the recursive step of calling multiples from within itself. I know that recursion needs a base case to allow it to exit, but I am completely stuck here and would appreciate some direction.

推荐答案

CLP(FD) 在这里非常有帮助:

CLP(FD) is very helpful here:

:- use_module(library(clpfd)).

multiple(Multiplicand, Max, Multiple) :-
    MaxMultiplier #= Max // Multiplicand,
    label([MaxMultiplier]),
    Multiplier in 1 .. MaxMultiplier,
    Multiple #= Multiplier * Multiplicand,
    label([Multiple]).

?- multiple(4, 12, M).
M = 4 ;
M = 8 ;
M = 12.

?-

在这种情况下,使用 CLP(FD),您还可以将第一个参数作为变量进行查询:

With CLP(FD) in this case, you can also query with the first argument as a variable:

|?- multiple(N, 12, 8).
N = 8 ;
N = 4 ;
N = 2 ;
N = 1.

或者乘数和结果:

?- multiple(N, 4, M).
N = M, M = 3 ;
N = M, M = 4 ;
N = M, M = 2 ;
N = 2,
M = 4 ;
N = M, M = 1 ;
N = 1,
M = 2 ;
N = 1,
M = 3 ;
N = 1,
M = 4.

?-

如果你想把它们收集到一个列表中,你可以使用findall/3:

If you want to collect them in a list, you can use findall/3:

?- findall(Multiple, multiple(4, 12, Multiple), Multiples).
Multiples = [4, 8, 12].

?-

这篇关于Prolog - 低于上限的数的倍数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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