RosettaCodeData/Task/Hailstone-sequence/Sidef/hailstone-sequence.sidef

25 lines
547 B
Plaintext
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

func hailstone (n) {
var sequence = [n]
while (n > 1) {
sequence << (
n.is_even ? n.div!(2)
 : n.mul!(3).add!(1)
)
}
return(sequence)
}
 
# The hailstone sequence for the number 27
var arr = hailstone(var nr = 27)
say "#{nr}: #{arr.first(4)} ... #{arr.last(4)} (#{arr.len})"
 
# The longest hailstone sequence for a number less than 100,000
var h = [0, 0]
for i (1 .. 99_999) {
(var l = hailstone(i).len) > h[1] && (
h = [i, l]
)
}
 
printf("%d: (%d)\n", h...)