检查一个数是否为质数的 Prolog 程序

编程入门 行业动态 更新时间:2024-10-25 00:30:04
本文介绍了检查一个数是否为质数的 Prolog 程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我根据质数只能被1和它本身整除的逻辑编写了以下程序.所以我只是经历了将它除以所有大于一且小于自身的数字的过程,但我似乎遇到了问题,因为我将所有输入的数字都设为真.这是我的代码...

I wrote the following program based on the logic that a prime number is only divisible by 1 and itself. So I just go through the process of dividing it to all numbers that are greater than one and less than itself, but I seem to have a problem since I get all entered numbers as true. Here's my code...

divisible(X,Y) :- Y < X, X mod Y is 0, Y1 is Y+1, divisible(X,Y1). isprime(X) :- integer(X), X > 1, \+ divisible(X,2).

提前致谢:)

推荐答案

我是 Prolog 的初学者,但设法解决了您的问题.

I'm a beginner in Prolog but managed to fix your problem.

divisible(X,Y) :- 0 is X mod Y, !. divisible(X,Y) :- X > Y+1, divisible(X, Y+1). isPrime(2) :- true,!. isPrime(X) :- X < 2,!,false. isPrime(X) :- not(divisible(X, 2)).

主要问题是声明X mod Y is 0.谓词is有两个(左右)参数,但左边的参数必须是一个常量或一个在谓词执行时已经统一的变量.我只是交换了这些值.其余代码用于检查数字 2(质数)和小于 2 的数字(非质数)

The main issue was the statement X mod Y is 0. Predicate is has two (left and right) arguments, but the left argument has to be a constant or a variable that is already unified at the moment that the predicate is executing. I just swapped these values. The rest of the code is for checking number 2 (which is prime) and number less than 2 (that are not primes)

我忘了提到比较 Y <X 有问题,因为您想测试 2 和 X-1 之间的所有数字,该比较包括 X.

I forgot to mention that the comparison Y < X is buggy, because you want to test for all numbers between 2 and X-1, that comparison includes X.

更多推荐

检查一个数是否为质数的 Prolog 程序

本文发布于:2023-11-29 22:51:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647860.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:质数   个数   程序   Prolog

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!