solutions/cw3/collatz2.while
author Christian Urban <christian.urban@kcl.ac.uk>
Fri, 22 Nov 2024 12:42:07 +0000
changeset 974 0cb4bf2469d1
parent 894 02ef5c3abc51
permissions -rw-r--r--
updated
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
864
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
     1
// Collatz series
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
     2
//
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
     3
// needs writing of strings and numbers; comments
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
     4
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
     5
bnd := 1;
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
     6
while bnd < 101 do {
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
     7
  write bnd;
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
     8
  write ": ";
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
     9
  n := bnd;
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    10
  cnt := 0;
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    11
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    12
  while n > 1 do {
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    13
    write n;
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    14
    write ",";
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    15
    
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    16
    if n % 2 == 0 
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    17
    then n := n / 2 
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    18
    else n := 3 * n+1;
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    19
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    20
    cnt := cnt + 1
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    21
  };
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    22
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    23
  write " => ";
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    24
  write cnt;
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    25
  write "\n";
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    26
  bnd := bnd + 1
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    27
}