PROGRAM 2
-- Filename: prog1b.adb Author: Anthony F. Ortiz -- This program finds and displays the integer n between 2 and 500 that -- generates the longest hailstone sequence. with Text_IO; use Text_IO; procedure Hailstones is package Int_IO is new Integer_IO (Integer); use Int_IO; Hailstone : Integer; -- Stores current hailstone. Count_N : Integer := 2; -- Starting sequence for hailstone. -- Initialize to 2. Count_Terms : Integer := 1; -- Count # of terms in current hailstone. -- Initialize to 1. Max_Hailstone : Integer := 0; -- Maximum hailstone sequence. -- Initialize to 0. Max_Terms : Integer := 0; -- Maximum # of terms in this sequence. -- Initialize to 0. begin -- Stop loop when the starting sequence is greater than 500. while (Count_N <= 500) loop -- Set next starting hailstone. Hailstone := Count_N; -- Stop loop when hailstone = 1. while (Hailstone /= 1) loop -- If hailstone is even, use formula 1 to get next -- hailstone. -- If hailstone is odd, use formula 2 to get next -- hailstone. if (Hailstone mod 2 = 0) then Hailstone := Hailstone / 2; else Hailstone := Hailstone * 3 + 1; end if; -- Count number of terms in current hailstone sequence. Count_Terms := Count_Terms + 1; end loop; -- If current number of terms is greater than the -- maximum number of terms, the greatest hailstone = -- the current starting sequence of hailstone and the -- maximum number of terms is equal to the current -- number of terms. if (Count_Terms > Max_Terms) then Max_Hailstone := Count_N; Max_Terms := Count_Terms; end if; -- Compute number of next starting sequence and -- set number of terms equal to 1. Count_N := Count_N + 1; Count_Terms := 1; end loop; -- Display greatest hailstone sequence and it's # of terms. Put ("the greatest hailstone sequence is "); Put (Max_Hailstone); New_Line; Put ("the number of terms is "); Put (Max_Terms); end Hailstones; -- outfile: prog1b.out the greatest hailstone sequence is 327 the number of terms is 144
BACK TO CS3660 PAGE.