今天因为看到编程之美上程序理解和时间分析,因此百度了一下验证自己的思路,偶然发现这位博友的文章,其中描述了另一道程序理解题。具体见http://blog.youkuaiyun.com/jcwkyl/article/details/3889802。
原题目如下:
We can use axioms to calculate programs just like what we do in algebras. Dijkstra is the one who advocates such constructive approach whereby a program is designed together with its correctness proof. In short, one has to start from a given postcondition Q and then look for a program that establishes Q from the precondition. Often, analyzing Q provides interesting hints to finding the program. This approach is quite different from the well known Hoare Logic.
For example, the following program is calculated by Dijkstra's approach. Unfortunately, its annotation is lost so that its function is hard to grasp. You are to help with finding the final value of the variable c. Note that the program is designed under 128-bit architecture.
Exp 1.0:
#include<cstdio>
int main(void)
{
int x = 987654321, c = 0, d = 1, e = 6;
while(x--){
c += d,
d += e,
e += 6;
}
printf("%d/n", c);
return 0;
}
自己试了三次就能猜到,该段程序的作用是产生x^3的结果。但是这样一个数学运算怎么转化成该算法呢?首先观察到三个数的加运算,因此就想到三个数列,若a+b=c,c+d=e,a,c,e构成了一个数列,则b,d也构成一个数列。
该程序产生的基础是三个数列:
设三个连续的整数i,i+1,i+2;
则三次幂分别为i^3,(i+1)^3,(i+2)^3
分别做差得到两个整数(i+1)^3-i^3=3*i^2+3*i+1;
(i+2)^3-(i+1)^3=3*(i+1)^2+3*(i+1)+1;
这两个数又构成了一个数列:3*i^2+3*i+1,3*(i+1)^2+3*(i+1)+1;
对两者做差得到6*(i+1);
令i=0,则得到起始条件为c=0,d=1,e=6,程序中的描述就是按照上面三个数列得到的结果。