Prolog ,需要从列表中找出合数并求和 [英] Prolog , Need to find out composite number from a list and sum

查看:102
本文介绍了Prolog ,需要从列表中找出合数并求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 prolog 的新手,当用户输入数字列表时,它只会对合数求和.复合数:4,6,8 ... etc.到目前为止,我在 prolog 中完成了列表的总和.但是我真的遇到了问题,如何在 prolog 中找到合数?

I am new in prolog, when user input list of number it will only sum the composite number. composite Number: 4,6,8 ... etc. So far I done sum of list in prolog.But really got problem how I can find composite number in prolog?

可以通过这个求和

list_sum( []          , 0        ) .
list_sum( [Head|Tail] , TotalSum ) :-
  list_sum(Tail,Sum1) ,
  Total = Head+Sum1 .

推荐答案

您需要添加一个谓词 is_composite/1 如果其参数是合数,则该谓词会成功.这就是我要做的:

You need to add a predicate is_composite/1 that succeed if its argument is a composite number. This is how I'd do it :

sum_of_composite_numbers( Ns , S ) :-
  sum_of_composite_numbers( Ns , 0 , S )
  .

sum_of_composite_numbers( [] , R , R ) .
sum_of_composite_numbers( [N|Ns] , T , R ) :-
  ( is_composite(N) -> T1 = T+N ; T1 = T ) ,
  sum_of_composite_numbers( Ns , T1 , R )
  .

合数是:

一个正整数,它至少有一个正除数,而不是 1 或数本身.换句话说,合数是任何大于 1 的正整数不是质数 [维基百科].

a positive integer that has at least one positive divisor other than one or the number itself. In other words, a composite number is any positive integer greater than one that is not a prime number [Wikipedia].

当然,质数是它的逆数,

And a prime number, of course, is its converse,

一个大于 1 的自然数,除了 1 和它本身之外没有其他正约数.大于 1 且不是质数的自然数称为合数.[维基百科]

a natural number greater than 1 that has no positive divisors other than 1 and itself. A natural number greater than 1 that is not a prime number is called a composite number. [Wikipedia]

因此,定义合数的一种方法是检查素数,例如:

So one way of defining a composite number would be to check for primeness, something like:

is_composite(N) :- N > 1 , \+ is_prime(N) .

关于如何确定素数的方法有很多.你应该能够弄清楚.

There's lots out there on how to determine primeness. You should be able to figure it out.

这篇关于Prolog ,需要从列表中找出合数并求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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