Digital River

(A problem set for the BIO of 1999.)

Before tackling this problem you should read the notes on functions.

A digital river is defined as a sequence of numbers where the number following any number n is n + the sum of its digits. For example, 12 is followed by 15 (12 + 1 + 2) and 15 is followed by 21.

Rivers can meet, in the case of a digital river this will be where two rivers share the same number. Every digital river will eventually meet river 1, 3 or 9. The problem is to write a program that inputs a value n (use integer at first and then try int64 for some big numbers).

The first step is to write a function that calculates the next number in a river.

function next_river(n: integer): integer;
var s: integer;
begin
    s := n;
    while s > 0 do begin
        n := n + (s mod 10);
        s := s div 10;
    end;
    next_river := n;
end;

We can now produce rivers of numbers by calling next_river(a). This calculates values in the digital rivers for 1, 3 and 9 up to a value supplied by the user (n). If n does not equal one of the values returned by the three digital rivers then the next value of n is calculated using the next_river function. This is then compared with the values in rivers 1, 3 and 9 again and if there is still no match then the next values of those rivers are found, and so on.

procedure part1a;
var river1, river3, river9: integer;
begin
    { We will use these variables to follow the routes of rivers 1, 3 and 9 }

    river1 := 1; river3 := 3; river9 := 9;

    { If we have not found a match, move along each river until we meet or
      pass n.  If we still haven't met n, move one step along river n. }

    while (n <> river1) and (n <> river3) and (n <> river9) do
      begin
        while river1 < n do river1 := next_river( river1 );
        while river3 < n do river3 := next_river( river3 );
        while river9 < n do river9 := next_river( river9 );
        if (n <> river1) and (n <> river3) and (n <> river9) then
            n := next_river( n );
      end;

    { Show the solution }
    if river1 = n then writeln( 'First meets river 1 at ', n );
    if river3 = n then writeln( 'First meets river 3 at ', n );
    if river9 = n then writeln( 'First meets river 9 at ', n );
end;

A procedure is used here because there is no single value to return. You need to implement this code in Delphi.

Questions continue at the BIO site.

Back