Created
July 28, 2013 06:28
-
-
Save bibby/6097643 to your computer and use it in GitHub Desktop.
A solution to finding the smallest integer with a multiplicative persistence of 5 (to 9) for Erlang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
% A solution to a puzzle in Martin Gardner's book | |
% The Colossal Book of Short Puzzles and Problems, | |
% | |
% bibby <bibby@bbby.org> | |
% | |
% Puzzle: | |
% A number's persistence is the number of steps required | |
% to reduce it to a single digit by multiplying all its | |
% digits to obtain a second number, then multiplying all | |
% the digits of that number to obtain a third number, and | |
% so on until a one-digit number is obtained. For example, | |
% 77 has a persistence of four because it requires four | |
% steps to reduce it to one digit: 77-49-36-18-8. The | |
% smallest number of persistence one is 10, the smallest | |
% of persistence two is 25, the smallest of persistence | |
% three is 39, and the smaller of persistence four is 77. | |
% What is the smallest number of persistence five? | |
% | |
% Solution: gardner:solve(5). | |
% Want more? [[N,gardner:solve(N)] || N <- lists:seq(0,8)]. | |
-module(gardner). | |
-export([solve/1, persistence/1]). | |
% solve/1 | |
% Get the lowest integer with persistence P | |
solve(P)-> | |
solve(P, 0). | |
% solve/2 | |
solve(P, I)-> | |
case persistence(I) of | |
P-> I; | |
_-> solve(P, 1+I) | |
end. | |
% persistence/1 | |
% Get the multiplicative persistence of integer N | |
persistence(N)-> | |
persistence(N, 0). | |
% persistence/2 | |
persistence(N, Rounds) when N < 10 -> | |
Rounds; | |
persistence(N, Rounds)-> | |
persistence(integer_to_list(N), 1, Rounds + 1). | |
% persistence/3 | |
persistence([], Product, Rounds) when Product > 9 -> | |
% io:format("round ~p product = ~p~n", [Rounds, Product]), | |
persistence(integer_to_list(Product), 1, Rounds + 1); | |
persistence([], _Product, Rounds)-> | |
Rounds; | |
persistence([H|T], Product, Rounds)-> | |
% io:format("H= ~p~n",[H]), | |
persistence( T, Product * (H-$0), Rounds). | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment