Here's my Ruby novice solution -- Works for the known oddballs (4879, 5292, 38962). Prepending '0' to odd-sized numbers inspired by others here.
defkaprekar?(k)s=k.to_s.size# s = nr. of digits in kk_sq=(k**2).to_s# k_sq = square of k (String)k_sq.prepend("0")if(k_sq.size.even?==false)# prepend '0' to odd-sized numbersifk_sq[s-1]=="0"# if digit 's-1' is 0, loop different combinations(0..s).eachdo|x|part1=k_sq[0..x-1].to_ipart2=k_sq[x..-1].to_ireturntrueif(k==part1+part2)endelse# if not, split before digit 's' (Integers)part1=k_sq[0..s-1].to_ipart2=k_sq[s..-1].to_ireturntrueifk==(part1+part2)endfalse# else returns falseend
Here's my Ruby novice solution -- Works for the known oddballs (4879, 5292, 38962). Prepending '0' to odd-sized numbers inspired by others here.
I don't like the exceptions (4879, 5292, 38962...) -- it feels like they don't belong in the sequence. And look how pretty the code is without them!