Sum digits till Square
Perl 6, 60 bytes
{$/=[$^x,*.polymod($^y xx*).sum*($y-1)...($y-1)²];$/-1,|$/}
Expanded:
{ # bare block lambda with placeholder parameters 「$x」 「$y」
$/ = [ # store in 「$/」 ( so that we don't have to declare it )
# generate a sequence
$^x, # declare first parameter, and seed sequence generator
# Whatever lambda
*\ # the parameter to this lambda
.polymod( # broken down with a list of moduli
$^y # declare second parameter of the outer block lambda
xx * # an infinite list of copies of it
)
.sum
*
( $y - 1 )
# end of Whatever lambda
... # repeat until it reaches
( $y - 1 )²
];
# returns
$/ - 1, # count of values minus one
|$/ # Slip 「|」 the list into the result
}
Usage:
# store it in the lexical namespace so that it is easier to understand
my &code = {$/=[$^x,*.polymod($^y xx*).sum*($y-1)...($y-1)²];$/-1,|$/}
say code 739, 7; # (2 739 42 36)
say code 1712, 19; # (3 1712 360 648 324)
Jelly, 14 13 bytes
-1 byte by printing as it loops (Ṅ
replacing a chain separation, µ
and concatenation ;
)
Ṅb⁹S×⁹’¤µÐĿL’
TryItOnline!
How?
Ṅb⁹S×⁹’¤µÐĿL’ - Main link: x, y
µÐĿ - loop monadically until results are no longer unique and collect
Ṅ - print z (initially x), then result of previous loop and return z
⁹ - right argument (y, even though monadic)
b - left to base right
S - sum (the result was a list of base y digits)
¤ - nilad followed by link(s) as a nilad
⁹’ - y decremented
× - multiply
L - length(z)
’ - decrement
- implicit print
The alternative 13 byter prints each input to the loop plus a line feed (Ṅ
), and finally implicitly prints the decremented count of the collected results, removing the need for a monadic chain separation (µ
) and concatenation (;
).
C, 116 113 bytes
-3 bytes for recalculating square each time
s,t,i;f(x,y){s=y-(i=1);while(x-s*s){t=0;++i;printf("%d ",x);while(x)t+=x%y,x/=y;x=t*y-t;}printf("%d %d ",x,i-1);}
Ungolfed and usage:
s,t,i;
f(x,y){
s=y-(i=1);
while(x-s*s){
t=0;
++i;
printf("%d ",x);
while(x)
t+=x%y, //add the base y digit
x/=y; //shift x to the right by base y
x=t*y-t;
}
printf("%d %d ",x,i-1);
}
main(){
f(739,7);puts("");
f(1712,19);puts("");
}