简体   繁体   中英

Prolog calculation on a list

I am new to prolog so bear with me,

So I have some code in which I am grabbing all the prime numbers up to a certain number.

primes_up_to(X,L):-
    findall(Y,
        (between(2,X,Y), is_prime(Y) ),
        L).

I now want to grab that list and check if each of the prime numbers can divide into X, so I can perform factorisation on it.

Here's my code thus far.

factorise(X, F):-
    X > 3,
    primes_up_to(X, L),
    write(L),

How do I use L to check if a given list element can divide into X

I assume i'd have to write someone like this:

0 is ListElement mod X

But I'd need to do that for each element

You write "factorization" so I suppose you're interested in known the multiplicity of factors.

I propose the following factors/3

factors(1, _, []).

factors(Num, [H|Tp], [H|Tf]) :-
  Num > 1,
  0 is mod(Num,H),
  Quot is Num // H,
  factors(Quot, [H|Tp], Tf).

factors(Num, [H|Tp], Tf) :-
  Num > 1,
  \+ 0 is mod(Num,H),
  factors(Num, Tp, Tf).

If you aren't interested in multiplicity of factors, the code can be simpler

factors(_, [], []).

factors(Num, [H|Tp], [H|Tf]) :-
  0 is mod(Num,H),
  factors(Num, Tp, Tf).

factors(Num, [H|Tp], Tf) :-
  \+ 0 is mod(Num,H),
  factors(Num, Tp, Tf).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM