Patrick
Patrick

Reputation: 185

Ada - Type conversion, exit when loop

Ada 2012.

I have this definition :

with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;
package body Primes is
   function is_prime(n : Integer) return Boolean
   is
      i : Integer := 5;
   begin
      if n <= 3 then
         return n > 1;
      elsif n mod 2 = 0 or else n mod 3 = 0 then
         return false;
      else
         --for i in 5 .. Sqrt()n + 1 
         loop
            if n mod i = 0 or else n mod (i + 2) = 0 then
               return false;
            end if;
            exit when i >= Sqrt(n) + 1;
            i := i + 6;
         end loop;
         return true;
      end if;

   end is_prime;

end Primes;

That checks whether n is prime or not. The this is line:

exit when i >= Sqrt(n) + 1;

Provides errors

expected type "Standard.Float"
found type "Standard.Integer"

I've been trying to Float'Value() on all parts of the statement, but then I got some error regarding what I think is exit when type (String). Now I'm stuck at this thing and can't get it to compile. Everything else is fine and doesn't need to be reviewed.

The reason why I used loop -> exit when -> end loop is because Ada doesn't support For loop with a specified step like for example Java:

for (int i = 5; i < Math.sqrt(n) + 1; i +=6)

Upvotes: 0

Views: 2338

Answers (2)

ajb
ajb

Reputation: 31699

Simon's answer is a lot more efficient, but to demonstrate how you would do this the way you're trying to do it:

        exit when Float(i) >= Sqrt(Float(n)) + 1.0;

Ada simply does not automatically convert integers to floats the way some languages do. (That also means it won't convert the integer literal 1 to a Float since a Float is needed for the predefined + operator on Float. You could use a type conversion, Float(1), instead of 1.0.)

Also, if you do things this way, compute Sqrt(Float(n)) outside the loop and save it in a variable (or something equivalent). There's no point in calling Sqrt over and over on the same value inside the loop. (Yeah, I know, someone will complain about premature optimization...)

MORE: This example shows how to achieve a type conversion. Float'Value doesn't do anything like that. If you look up "Value attribute" in the RM Index, you'll see that the 'Value attribute is a function that takes a String argument, and returns a number whose image is the String--i.e. it parses the string and returns a number, in this case a Float.

Upvotes: 3

Simon Wright
Simon Wright

Reputation: 25511

The square-root function in Ada.Numerics.Generic_Elementary_Functions (of which Ada.Numerics.Elementary_Functions is an instantiation) is

function Sqrt (X : Float_Type'Base) return Float_Type’Base;

which only handles floating-point types.

You might be able to use

exit when i * i >= n;

(mind you, if i * i was equal to n then n wouldn’t be prime; some attention needed to this terminating condition, I think)

Upvotes: 2

Related Questions