PageRenderTime 14ms CodeModel.GetById 1ms app.highlight 8ms RepoModel.GetById 2ms app.codeStats 0ms

/seven.adb

http://github.com/rtyler/euler-ada
Ada | 43 lines | 27 code | 6 blank | 10 comment | 5 complexity | 643422ca0cbef34df4975dca06538c0f MD5 | raw file
 1--
 2--  Project Euler problem #7
 3--
 4--  By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see
 5--  that the 6th prime is 13.
 6--
 7--  What is the 10001st prime number?
 8--
 9
10with Ada.Numerics.Elementary_Functions,
11     Ada.Text_IO;
12
13use Ada.Numerics.Elementary_Functions,
14    Ada.Text_IO;
15
16procedure Seven is
17
18    function Is_Prime (Input : in Natural) return Boolean is
19        -- Using the "Trial Division" method detailed in this Wikipedia entry:
20        -- https://secure.wikimedia.org/wikipedia/en/wiki/Prime_number#Trial_division
21        Ceiling : constant Natural := Natural (Sqrt (Float (Input)));
22    begin
23        for Index in 2 .. Ceiling loop
24            if (Input mod Index) = 0 then
25                return false;
26            end if;
27        end loop;
28        return true;
29    end Is_Prime;
30
31    Count : Natural := 0;
32begin
33    for N in 2 .. Natural'Last loop
34        if Is_Prime (N) then
35            Count := (Count + 1);
36
37            if Count = 10_001 then
38                Put_Line (Natural'Image (N) & " is prime");
39                return;
40            end if;
41        end if;
42    end loop;
43end Seven;