Search code examples
prologprimesnumber-theory

Prime factorization in prolog


I'm new to Prolog. I read this code which finds prime factors of an integer:

factors(1,[1]) :-
   true, !.
factors(X,[Factor1|T]) :-
   X > 0,
   between(2,X,Factor1), 
   NewX is X // Factor1, (X mod Factor1) =:= 0,
   factors(NewX,T), !.

And changed it to this one:

factors(1,[[1,1]]) :-
   true, !.
factors(X,[Factor1|T]) :-
   X > 0,
   (  is_list(Factor1),
      length(Factor1, 2),
      Factor1 = [Base|A],
      A = [Pow], 
      between(2,X,Base),
      between(1,100,Pow), 
      NewX is X / (Base ** Pow),
      (X mod Base) =:= 0,
      (NewX mod Base) =\= 0
   ),
   factors(NewX,T), !.

Well the first one works perfect, but the latter doesn't respond to queries. i.e. when I enter:

factors(2,[[2,1],[1,1]]).  

I get 'true', but when I enter:

factors(2,X).  

I get 'false'.


Solution

  • Because Base and Pow aren't bound to anything yet (they are parts of the X that you pass), you can't compute NewX (and the betweens might not work, either).