Answer the question
In order to leave comments, you need to log in
How to get the second factor from an equation in Prolog?
Well... How do you say equations? It is known that a certain number X is the result of multiplying two prime numbers. At first I tried 143 = prime(P) * prime(_)
But since there are 2 unknowns, I tried 143 = prime(P) * 13
on the idea, Prolog should take 143 / 13 = 11 from here and check if the number 11 is prime. But it 143 = P * 13
doesn't even work!
Here is the code: *poke*
PS {
Prime checker working
I don't think *(P, 13) is better than P * 13
SWI-Prolog
}
Answer the question
In order to leave comments, you need to log in
I didn’t write from scratch, I spied part of the code on the net (because “I haven’t picked up checkers for a long time”), but the idea is quite simple: you need to figure out the principles of inference in the prologue, in the sense that candidates must be generated by some process .
By reading The Art of Prolog
The idea is really simple, you need to write "generators" that will give candidates for the solution. In the code below, these are lists of prime numbers less than the given one, then the candidate is just a prime number from the list, pulled out by the standard member function
. The output is done like this
?- factorization(143,P1,P2).
1113
P1 = 11,
P2 = 13 .
?- factorization(25,P1,P2).
55
P1 = P2, P2 = 5 .
divisible(X,Y) :- 0 is X mod Y, !.
divisible(X,Y) :- X > Y+1, divisible(X, Y+1).
is_prime(2) :- true,!.
is_prime(X) :- X < 2,!,false.
is_prime(X) :- not(divisible(X, 2)).
factorization(X,P1,P2) :- prime_list(2,X,L), member(P1,L), member(P2,L), is_prime(P1), is_prime(P2), X is P1 * P2.
prime_list(A,B,L) :- A =< 2, !, p_list(2,B,L).
prime_list(A,B,L) :- A1 is (A // 2) * 2 + 1, p_list(A1,B,L).
p_list(A,B,[]) :- A > B, !.
p_list(A,B,[A|L]) :- is_prime(A), !, next(A,A1), p_list(A1,B,L).
p_list(A,B,L) :- next(A,A1), p_list(A1,B,L).
next(2,3) :- !.
next(A,A1) :- A1 is A + 2.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question