Repeat a string: Difference between revisions
Content added Content deleted
No edit summary |
|||
Line 76: | Line 76: | ||
set final_string to "" |
set final_string to "" |
||
repeat 5 times |
repeat 5 times |
||
set final_string to final_string & str |
|||
end repeat</lang> |
end repeat</lang> |
||
For larger numbers of repetitions, however, it proves significantly faster to progressively double a copy of the original string (concatenating it with itself). Intermediate stages of doubling are appended to an accumulator wherever required for binary composition of the target number. |
|||
See the technique of 'Egyptian Multiplication' described in the Rhind Mathematical Papyrus at the British Museum. |
|||
{{trans|JavaScript}} |
|||
<lang AppleScript>on run |
|||
nreps("ha", 50000) |
|||
end run |
|||
-- String -> Int -> String |
|||
on nreps(s, n) |
|||
set o to "" |
|||
if n < 1 then return o |
|||
repeat while (n > 1) |
|||
if (n mod 2) > 0 then set o to o & s |
|||
set n to (n div 2) |
|||
set s to (s & s) |
|||
end repeat |
|||
return o & s |
|||
end nreps |
|||
</lang> |
|||
=={{header|Applesoft BASIC}}== |
=={{header|Applesoft BASIC}}== |