How to resolve the algorithm Hailstone sequence step by step in the Futhark programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Hailstone sequence step by step in the Futhark programming language

Table of Contents

Problem Statement

The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:

The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.

This sequence was named by Lothar Collatz in 1937   (or possibly in 1939),   and is also known as (the):

The hailstone sequence is also known as   hailstone numbers   (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Hailstone sequence step by step in the Futhark programming language

Source code in the futhark programming language

fun hailstone_step(x: int): int =
  if (x % 2) == 0
  then x/2
  else (3*x) + 1

fun hailstone_seq(x: int): []int =
  let capacity = 100
  let i = 1
  let steps = replicate capacity (-1)
  let steps[0] = x
  loop ((capacity,i,steps,x)) = while x != 1 do
    let (steps, capacity) =
      if i == capacity then
        (concat steps (replicate capacity (-1)),
         capacity * 2)
      else (steps, capacity)
    let x = hailstone_step x
    let steps[i] = x
    in (capacity, i+1, steps, x)
  in #1 (split i steps)

fun hailstone_len(x: int): int =
  let i = 1
  loop ((i,x)) = while x != 1 do
    (i+1, hailstone_step x)
  in i

fun max (x: int) (y: int): int = if x < y then y else x

fun main (x: int) (n: int): ([]int, int) =
  (hailstone_seq x,
   reduce max 0 (map hailstone_len (map (1+) (iota (n-1)))))


  

You may also check:How to resolve the algorithm Object serialization step by step in the J programming language
You may also check:How to resolve the algorithm Integer comparison step by step in the Common Lisp programming language
You may also check:How to resolve the algorithm Vector products step by step in the REXX programming language
You may also check:How to resolve the algorithm Display a linear combination step by step in the Go programming language
You may also check:How to resolve the algorithm Greatest common divisor step by step in the Euler programming language