如何证明algorithm是正确的

前记:数据库hw3里有一个问题,让证明textbook里某个算法是correct的。第一反应觉得这个题目好奇怪,教材上给的算法肯定是正确的啊,有什么好证明的。冷静一想,自己太naive了。 于是在网上找了很多相关的资料,整理如下。

Scheme: 

1. All cases are covered: completeness 

Show all possible inputs are processed by the algorithm, may be trivial 

2. For a given (arbitrary) case, it is correctly processed: correctness 

May need to cover individually all branches/cases of the algorithm 

For each case, show the processing generates the expected output 

3. n all cases, the algorithm exits: termination

Example:

Def naive(a, b): 

x = a; y = b

z = 0

  while x > 0:

z = z + y

x = x - 1

return z

Prove the correctness of naive(a, b) 

        loop invariant:  naive(a, b) = ab , ab = xy + z

Base case: 

    First time through, x = a, y = b, z = 0

    ab = xy + z =  ab + 0 (correct! Loop invariant holds on loop entry )

Inductive step:

    if ab = xy + z before

    then ab = x’y’ + z’ after

    According to the algorithm, we could get:

    x’ = x-1, y’ = y, z’ = z+y

    x’y’ + z’ = (x-1)y + (z+y) = xy + z = ab (correct!)

We know ab=xy + z, so? (terminal)

    x = 0,  xy + z = ab

    0*y + z = ab   ==> z = ab

Reference: 

1.  http://www-inst.cs.berkeley.edu/~cs170/fa14/tutorials/tutorial1.pdf

  重点1:why we use inductive? 

  重点2: 1)  construct a loop invariant;  2) prove that loop invariant is inductive;  3) prove correctness property using loop invariant

2.  http://web.cs.ucla.edu/~pouchet/lectures/doc/888.11.algo.6.pdf

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值