isqrt.c 739 Bytes
Newer Older
MARCHE Claude's avatar
MARCHE Claude committed
1 2 3 4
/* run.config
   OPT: -journal-disable -jessie3
*/

MARCHE Claude's avatar
MARCHE Claude committed
5 6 7 8

//@ logic integer sqr(integer x) = x * x;

/*@ requires x >= 0;
MARCHE Claude's avatar
MARCHE Claude committed
9
  @ requires x <= 1000000000; // to prevent integer overflow
10
  @ ensures \result >= 0 && sqr(\result+0) <= x && x < sqr(\result + 1);
MARCHE Claude's avatar
MARCHE Claude committed
11 12 13
  @*/
int isqrt(int x) {
  int count = 0, sum = 1;
14
  /*@ loop invariant count >= 0 && x >= sqr(count+0) && sum == sqr(count+1);
MARCHE Claude's avatar
MARCHE Claude committed
15
    @ loop variant  x - count;
MARCHE Claude's avatar
MARCHE Claude committed
16
    @*/
17
  while (sum <= x) { ++count; sum += 2 * count + 1; }
MARCHE Claude's avatar
MARCHE Claude committed
18 19 20
  return count;
}

21
#if 0
MARCHE Claude's avatar
MARCHE Claude committed
22

MARCHE Claude's avatar
MARCHE Claude committed
23 24 25 26 27 28 29 30 31
//@ ensures \result == 4;
int main () {
  int r;
  r = isqrt(17);
  //@ assert r < 4 ==> \false;
  //@ assert r > 4 ==> \false;
  return r;
}

32 33
#endif

MARCHE Claude's avatar
MARCHE Claude committed
34 35 36 37 38 39 40
/*
Local Variables:
compile-command: "frama-c -add-path ../.. -jessie3 isqrt.c"
End:
*/