Proggramming Languages assignment II

# Assignment II

Due date Tuesday October 2, 2001

```
This is an assignment in Ada. If you have never programmed in Ada before, you
can do the assignment on paper, with the understanding that syntax matters, and
that you have to read the text carefully to acquire the basics.

You can also install the compiler from the disk in the back of the book, or
use the GNAT system (instructions follow) installed on all the servers at
NYU.
----------------------

The following function determines naively whether a number is a prime or
a composite:

function Is_Prime (Val : Integer) return boolean is
begin
if Val = 2 then
return True;
else
for Div in 2 .. val loop
if Val mod Div = 0 then        --  found divisor
return False;
elsif Div * Div > Val then     --  no larger divisor
return True;
end if;
end loop;
end if;

return True;  -- redundant but suppresses warnings.
end Is_Prime;

a) Make sure you understand how this function works.

b) Write a procedure Build_Primes, that uses the previous function to
find all the prime numbers between 1 and 100. You can declare an array
of size 30 (larger than necessary) to hold these primes. Your program
will look as follows:

procedure Prime_Numbers is
All_Primes : array (1..50) of Positive;
Num_Primes : Positive;
--  how many actually appear between 1 and 100

function Is_Prime is ...
procedure Build_Primes is ...
begin
Build_Primes;
....   -- the next part of the assignment
end Prime_Numbers;

that is to say, the array of primes is global to both subprograms.

c) Using the array of primes, write a procedure that prints the prime
factorization of a number. For example, if the input is 17, the
procedure prints:
17 is a prime

while if the input is 18, the procedure prints:

18 = 2 * 3^2

using the caret "^" to denote exponentiation.

In order to read and print integers in your program, you need to include the
following library files in the context of the program:

with Text_Io; use Text_Io;

After which you can write

Get (Val);  to read from input, and
Put (Val);  to print.

You can also print a full line as a string using Put_Line. To format
a line that contains the string representation of integers, the attribute
Image (to be discussed later) simplifies the task. So, assuming that
the value of variable Val is 17, we can write:

Put_Line (Integer'Image (17) & " is a prime");

The operator "&" denotes concatenation of strings.

For guidance, look at chapters 6 and 7 of the text by Barnes.
Enjoy!
```