summaryrefslogtreecommitdiff
path: root/Test/dafny1/pow2.dfy
blob: ad6a97376660739c685fe641def0b0f62d99798f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// RUN: %dafny /compile:0 /dprint:"%t.dprint" "%s" > "%t"
// RUN: %diff "%s.expect" "%t"

// This is a Dafny adaptation of a Coq program by David Pichardie.

function IsEven(n: int): bool
  requires 0 <= n;
  ensures IsEven(n) ==> n == (n/2)+(n/2);
{
  (n/2)*2 == n
}

function Square(n: int): int { n * n }

function pow2(n: int): int
  requires 0 <= n;
  ensures 0 <= pow2(n);
{
  if n == 0 then
    1
  else if IsEven(n) then
    Square(pow2(n / 2))
  else
    2*pow2(n-1)

}

function pow2_slow(n: int): int
  requires 0 <= n;
{
  if n == 0 then
    1
  else
    2*pow2_slow(n-1)
}

lemma Lemma(n: int)
  requires 0 <= n && IsEven(n);
  ensures pow2_slow(n) == Square(pow2_slow(n/2));
{
  if n != 0 {
    Lemma(n-2);
  }
}

lemma Theorem(n: int)
  requires 0 <= n;
  ensures pow2(n) == pow2_slow(n);
{
  if n == 0 {
  } else if (IsEven(n)) {
    Lemma(n);
    Theorem(n/2);
  } else {
    Theorem(n-1);
  }
}