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

25 lines
547 B
Text
Raw Permalink Normal View History

2016-12-05 23:44:36 +01:00
func hailstone (n) {
2017-09-23 10:01:46 +02:00
var sequence = [n]
2016-12-05 23:44:36 +01:00
while (n > 1) {
2017-09-23 10:01:46 +02:00
sequence << (
n.is_even ? n.div!(2)
 : n.mul!(3).add!(1)
)
2016-12-05 23:44:36 +01:00
}
2017-09-23 10:01:46 +02:00
return(sequence)
2016-12-05 23:44:36 +01:00
}
2017-09-23 10:01:46 +02:00
 
2016-12-05 23:44:36 +01:00
# The hailstone sequence for the number 27
2017-09-23 10:01:46 +02:00
var arr = hailstone(var nr = 27)
say "#{nr}: #{arr.first(4)} ... #{arr.last(4)} (#{arr.len})"
 
2016-12-05 23:44:36 +01:00
# The longest hailstone sequence for a number less than 100,000
2017-09-23 10:01:46 +02:00
var h = [0, 0]
for i (1 .. 99_999) {
2016-12-05 23:44:36 +01:00
(var l = hailstone(i).len) > h[1] && (
2017-09-23 10:01:46 +02:00
h = [i, l]
)
2016-12-05 23:44:36 +01:00
}
2017-09-23 10:01:46 +02:00
 
printf("%d: (%d)\n", h...)