CUDDLE calculation
Python 2, 56
f=lambda n,i=2,s='L':len(set(s))>10or-~f(n,i+1,s+`n**i`)
A recursive solution. Counts up exponents i
starting from 2
and accumulates the digits of powers n**i
into the string s
. When s
has all ten digits, returns True
, which equals 1
, and otherwise recurses and adds 1
. This turned out shorter than returning i
.
Calling the function on a number without a CUDDLE terminates with Internal error: RangeError: Maximum call stack size exceeded
. Numbers up to 255
that do output never need more than 15 iterations.
Because of Python 2's annoying habit of appending an L
to large numbers, we actually initialize the digit string to L
and check if the set size is at least 11. Python 3 saves 2 chars by not needing this, but loses 3 chars on using str
over backticks. Python 3.5 saves 2 more chars with set unpacking, saving a char over Python 2 in total:
f=lambda n,i=2,s='':len({*s})>9or-~f(n,i+1,s+str(n**i))
Pyth, 16 bytes
hf<9l{=+k^QTtS15
Try it online: Demonstration or Test Suite
Like other solutions, I use 15 as an upper limit. I believe that this is also the maximal CUDDLE. I tested all numbers up to 10.000.000, and there's no number with a CUDDLE greater than 15.
Numbers with a CUDDLE >= 10 are already quite rare. The only numbers with a CUDDLE of 15 are the numbers 2*10^k
. There are no numbers with a CUDDLE of 14 or 13, the CUDDLE 12 only appears for the numbers 6*10^k
, the CUDDLE 11 only for 5*10^k
.
So I think this code works perfectly for any natural number.
Prints an error message, if there is no solution.
Explanation:
hf<9l{=+k^QTtS15 implicit: Q = input number
k = empty string
tS15 the list [2, 3, 4, ..., 15]
f filter this list for elements T, which satisfy:
^QT compute Q^T
+k k + ^ (converts to string implicitly)
= k save the result in k
l{ k length of set of k (number of different chars)
<9 test if 9 is smaller than ^
h print the first number in the filtered list
(throws error if empty)
Ruby, 67 65 chars
->n{s='';[*2..99].index{|i|(s+="#{n**i}").chars.uniq.size==10}+2}
Works near-instantaneously for all the test cases, even the ones > 255.
Errors for numbers with no CUDDLE.
Explanation:
-> n { # define function with short lambda syntax
s = '' # the string we are storing the numbers in
[*2..99] # for all numbers from 2 to 99...
.index {|i| # find index of the number `i` for which...
(s+="#{n**i}") # after appending pow(n,i) to s...
.chars.uniq.size==10} # num of uniq chars in s is 10 (each digit)
+ 2 # add 2, because our index starts from 2
}