Find palindromic numbers in both binary and ternary bases: Difference between revisions

Line 1,419:
</pre>
between 6 and 7 I have shown progress() in action, which is constantly overwritten, and mesmerising to watch.
 
=== much simpler version ===
(slightly but not alot faster)
<lang Phix>function to_base(atom n, integer base)
string result = ""
while true do
result &= remainder(n,base)
n = floor(n/base)
if n=0 then exit end if
end while
return result
end function
 
procedure show(integer count, atom n)
string n2 = sq_add('0',to_base(n,2)),
n3 = sq_add('0',to_base(n,3)),
p2 = repeat(' ',(37-length(n2))/2),
p3 = repeat(' ',(23-length(n3))/2)
printf(1,"%2d: %12d %s%s%s %s%s\n",{count, n, p3,n3,p3, p2,n2})
end procedure
 
function createpalindrome3(integer n)
atom tot = 0, power3 = 1
string ternary = to_base(n,3)
for i=length(ternary) to 1 by -1 do
tot += ternary[i] * power3
power3 *= 3
end for
return tot + power3 + n*power3*3
end function
atom t0 = time()
printf(1,"%16s %15s %30s\n",{"decimal","ternary","binary"})
show(0,0)
show(1,1)
integer count = 2, n = 1
while count<6 do
atom n3 = createpalindrome3(n)
if remainder(n3,2) then
string n2 = to_base(n3,2)
if n2[$]=1 and n2=reverse(n2) then
show(count,n3)
count += 1
end if
end if
n += 1
end while
?elapsed(time()-t0)</lang>
{{out}}
<pre>
decimal ternary binary
0: 0 0 0
1: 1 1 1
2: 6643 100010001 1100111110011
3: 1422773 2200021200022 101011011010110110101
4: 5415589 101012010210101 10100101010001010100101
5: 90396755477 22122022220102222022122 1010100001100000100010000011000010101
"0.6s"
</pre>
 
=== much faster version ===
7,805

edits