I found a problem on a website and I tried to solve it, but I can't figure out where I did wrong.

Problem:

The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. Which starting number, under one million, produces the longest chain? NOTE: Once the chain starts the terms are allowed to go above one million.

my code...I wrote it in Pascal.

function f (var n:longint):longint; begin if n = 1 then f:= 1 else if n mod 2 = 0 then begin n:=n div 2; f:= 1+ f(n); end else if n mod 2 = 1 then begin n:= 3*n + 1; f:= 1+ f(n); end; end; var n,nr,max,secv:longint; begin max:=0; nr:=0; for n:= 1 to 1000000 do begin secv:=f(n); writeln('n= ',n,' ', 'secv= ', secv); if secv > max then begin max:=secv; nr:=n; end; end; writeln('nr:= ',nr); writeln('secventa maxima:= ',secv); end.

The compiling doesn't give any errors, but I just get an infinite loop cuz this is what the console looks like when i run the program.

I would really appreciate any help.

Thx.