2

I started learning Dafny and I just learned invariants. I've got this code:

function pot(m:int, n:nat): int
{
  if n==0 then 1
  else if n==1 then m
  else if m==0 then 0
  else pot(m,n-1) * m
} 
method Pot(m:int, n:nat) returns (x:int)
ensures x == pot(m,n)
{
  x:=1;
  var i:=0;
  if n==0 {x:=1;}
  while i<=n
  invariant i<=n;
  {
    x:=m*x;
    i:=i+1;
  }
}

And the given error is the following: "This loop invariant might not be maintained by the loop." I think I might need another invariant, but I think my code is correct other than that (I guess). Any help is appreciated. Thanks in advance.

Byakko
  • 33
  • 8

1 Answers1

2

A loop invariant must hold whenever the loop branch condition is evaluated. But on the last iteration of your loop, i will actually be n+1, so the loop invariant is not true then.

Changing the loop invariant to i <= n + 1 or changing the loop branch condition to i < n will fix this particular problem.

After that, you will still have some work to do to finish proving the method correct. Feel free to ask further questions if you get stuck.

James Wilcox
  • 5,307
  • 16
  • 25
  • First of all, thanks for answering me yet again, James! But yea, I tried what you said before but it didn't work so I thought the problem wasn't solved. I'll try later. Thanks. – Byakko Aug 18 '17 at 13:01
  • After fixing this problem, you will get a *different* error, which you still need to fix in order to finish verifying the method. – James Wilcox Aug 18 '17 at 15:55
  • Yeah, I noticed haha. I'm trying to fix it. – Byakko Aug 20 '17 at 00:18