Murdock
Murdock

Reputation: 123

Prolog Count divisors

I'm working on a predicate which will count the number of divisors for a given number. It won't count all of them, but enough for me to know that it has more than two sets of factors. Here is what I have:

countFactors([_,_,_,_X]):-!.
countFactors(Product, Count,Divisor, _X):-
     Divisor =< Product/2,
     Product mod Divisor = 0,
     NewC is Count + 1,
     NextD is Divisor + 1,
     countFactors(Product,NewC, NextD, NewC).

However, running countFactors(16,0,2,X). Simply returns false, whereas i would expect it to return X = 2

EDIT: Ok, so now I realise why it returns false: it works fine if the divisor in question is a factor, and recurses. However, if it isn't a factor, then it gives false, but doesn't increment to the next divisor, it just stops and returns false.

So my question is, how can I correct this?

Upvotes: 1

Views: 1471

Answers (1)

CapelliC
CapelliC

Reputation: 60034

There is some error in your code, I post some correction. Maybe you will need to do some minor modification.

%% count all factors of Product
%
countFactors(Product, Count, Divisor, Tot) :-
     Divisor > Product/2,
     !, Tot is Count.
countFactors(Product, Count, Divisor, Tot):-
     (   Product mod Divisor =:= 0
     ->  NewC is Count + 1
     ;   NewC is Count
     ),
     NextD is Divisor + 1,
     countFactors(Product, NewC, NextD, Tot).

Upvotes: 1

Related Questions