Prolog , Need to find out composite number from a

2019-09-21 04:25发布

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 .

标签: prolog
1条回答
Viruses.
2楼-- · 2019-09-21 04:59

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.

查看更多
登录 后发表回答