isqrt.c 738 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;
9
  @ requires x <= 1000000000; // not avoid 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 16
    @ loop variant  x - count; 
    @*/
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 23 24 25 26 27 28 29 30
//@ ensures \result == 4;
int main () {
  int r;
  r = isqrt(17);
  //@ assert r < 4 ==> \false;
  //@ assert r > 4 ==> \false;
  return r;
}

31 32
#endif

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