Skip to content

Instantly share code, notes, and snippets.

@sacdallago
Created August 19, 2015 13:56
Show Gist options
  • Save sacdallago/5c91271fe3ea2c05191e to your computer and use it in GitHub Desktop.
Save sacdallago/5c91271fe3ea2c05191e to your computer and use it in GitHub Desktop.
% Compute power of a number
power(1,0,_).
power(X,Y,C):- X1 is X+X, Y1 is Y-1, powerUp(X1,Y1,C).
powerUp(X,1,X).
powerUp(X,Y,C) :- X1 is X+X, Y1 is Y-1, powerUp(X1,Y1,C).
% Sum elements in list.
sum([],0).
sum([X|Y],C) :- sumHelp(Y,X,C).
sumHelp([],X,X).
sumHelp([X|Y],P,C) :- P1 is X+P, sumHelp(Y,P1,C).
% Converts a number into a list of its digits
convertNumber(Y,C) :- number_codes(Y,X),format('~s',[X]),normalize(X,C).
normalize([],[]).
normalize([X|X1],[Y|Y1]) :- Y is X-48, normalize(X1,Y1).
% Example application
% power(2,1000,X),convertNumber(X,Y),sum(Y,C).
end_of_file.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment