Prolog 查找 N 个素数 [英] Prolog Find N prime numbers

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

问题描述

Prolog 的递归函数有问题.我认为我没有正确实施它,需要帮助.

I have a problem with the recursive function of Prolog. I believe I am not implementing it right and need help.

我需要生成前 N 个素数并将其返回到列表中.生成素数不是问题,而是在列表中生成它是我的问题.

I need to generate the first N prime numbers and return it in a list. Generating the prime number is not an issue, but rather, generating it in a list is the issue I have.

这是相关代码的一部分:

This is the part of the relevant code:

genList(_, 0, _).
genList(X, N, PrimeList, PrimeList):-
    N > 0,
    isprime(X),
    X1 is X +1,
    N1 is N -1,
    genList(X1,N1,[X|PrimeList], [X|PrimeList]),!.
genList(X, N, PrimeList, PrimeList):-
    N>0,
    \+isprime(X),
    X1 is X + 1,
    genList(X1,N,PrimeList, PrimeList).

这是我在 Prolog 解释器中输入的内容:

This is what I type into the Prolog interpreter:

genList(1,N, [],L).

对于第一行,我如何制作基本情况,以便当 N=0 时,我停止递归?这是正确的吗?

For the 1st line, how do I make the base case such that when N=0, I stop recursing? Is this correct?

至于接下来的 2 个子句,我在逻辑编程方面遇到了困难.我绝对觉得这不是逻辑编程风格.

As for the next 2 clauses, I am having difficulty in thinking in terms of logic programming. I definitely feel that this is not logic programming style.

我想说,当isPrime(X)失败时,我们继续下一个数字而不保存任何东西,但是当isPrime(X)为真时,那么我们递归并继续下一个数字,保存X.

I want to say that when isPrime(X) fails, we continue to the next number without saving anything, but when isPrime(X) is true, then we recurse and continue to the next number, saving X.

我如何在 Prolog 中做到这一点?

How do I do that in Prolog?

推荐答案

首先,如果您只需要两个参数,则您的主谓词不需要 4 个参数.在这里,您需要最多 N 的第一个素数列表.所以 N 的参数和列表的参数就足够了:

First of all, you shouldn't need 4 arguments to your main predicate if you only want two. Here you want the list of the first primes up to N. So an argument for N and an argument for the list should be enough:

primeList(N, L) :-
    % eventually in the body a call to a worker predicate with more arguments

现在,您的逻辑是用这些术语解释的:

Now here, your logic is explained in those terms:

primeList(N, [N|L]) :-
    % If we're not at the base case yet
    N > 0,
    % If N is a prime
    isPrime(N),
    NewN is N - 1,
    % Let's recurse and unifie N as the head of our result list in the head
    % of the predicate
    primeList(NewN, L).

primeList(N, L) :-
    % Same as above but no further unification in the head this time.
    N > 0,
    % Because N isn't a prime
    \+ isPrime(N),
    NewN is N - 1,
    primeList(NewN, L).

为此,您必须添加基本案例

To that you'd have to add the base case

primeList(0, []).

你可以用如下方式重写:

You could rewrite that with cuts as follows:

primeList(0, []) :- !.
primeList(N, [N|L]) :-
    isPrime(N),
    !,
    NewN is N - 1,
    primeList(NewN, L).
primeList(N, L) :-
    NewN is N - 1,
    primeList(NewN, L).

这篇关于Prolog 查找 N 个素数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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