Execution time timeout for Perfect Numbers problem

Hi to everyone!

Traying to resolve Perfect Numbers problems

I checked the code and works for tests but execution time is around 23 second for large numbers tests and finally finish with time out message. Any idea to solve this problem without using between predicate?

classify(Number, perfect):- factors(Number, Number, [_|R]), sum_list(R, Number). 
classify(Number, abundant):- factors(Number, Number, [_|R]), sum_list(R, R2), Number < R2.
classify(Number, deficient):- factors(Number, Number, [_|R]), sum_list(R, R2), Number > R2.

factors(_, 1, [1]).
factors(N, Range, [Range|R]):- Range > 1, Range2 is Range - 1, 0 is mod(N, Range), factors(N, Range2, R).

factors(N, Range, R):- Range > 1, Range2 is Range - 1,  Mod is mod(N, Range), Mod \= 0, factors(N, Range2, R).

Thank you so much and have a lovely day! :pray:

The problem lies in the factors predicate testing a ton of numbers, even when you can already know that the number of a factor if it is a multiple of a previous factor. One approach that you can use is to test all factors up to the square root of N, and then do a second pass to find the factors that are multiples of those.