Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 views
in Technique[技术] by (71.8m points)

Prolog , Need to find out composite number from a list and sum

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?

Can find sum by this

list_sum( []          , 0        ) .
list_sum( [Head|Tail] , TotalSum ) :-
  list_sum(Tail,Sum1) ,
  Total = Head+Sum1 .
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 )
  .

A composite number is:

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,

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...