solutions/cw4/collatz2.while
author Christian Urban <christian.urban@kcl.ac.uk>
Fri, 04 Nov 2022 12:07:40 +0000
changeset 894 02ef5c3abc51
parent 864 solution/cw4/collatz2.while@b5b1bc0a603b
permissions -rw-r--r--
updatedHG: added solutions/cw5/fun_tokens.sc
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 < 100001 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
}