JOJ的2042面试题目的数学推导过程

来源:互联网 发布:js获取当前滚动条位置 编辑:程序博客网 时间:2024/06/02 23:24

Benny_Cen

 

JOJ的2042题目是一个程序理解题目,这个题目非常有意思,给出了下面一段C++源代码,要求计算出最后的输出结果,源代码如下:

#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;
}

原题目如下:

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.

代码就是上面那一段。

这个题目通过小数据计算可以看出规律:x=1, c = 1; x=2, c=8; x=3, c=27; x=4, c=64,于是可以猜测这段程序是用来计算x^3的。用计算器计算出987654321^3,提交上去就AC了。

这个题目是超级大牛SIYEE出的。但是为什么会得到这样神奇的结果?有数学推导方法吗?

有!而且是高中数学知识!这时候才知道高中数学是多么有用呵!

首先看这个程序:

int x = 987654321, c = 0, d = 1, e = 6;
     while(x--){
         c += d,
         d += e,
         e += 6;
     }

这里c,d,e充当了一个临时寄存器角色,不要被赋值语句迷惑了,其实c,d,e都是数列

首先在草稿纸上列出前几列:

x  0   1    2

c  0   1    8

d  1   7   19

e  6   12  18

 

然后在C语言描述中看:

(1)c的数列描述:

c(n) = 0;    n = 0

c(n) = c(n -1) + d(n - 1); n>=1

(2)d的数列描述:

d(n) = 1;    n = 0

d(n) = d(n -1) + e(n - 1); n>=1

(3)e的数列描述:

e(n) = 6(n+1)

由于e(n)已知,所以可以从这里入手:

计算d(n):

d(n) = d(n -1) + e(n - 1); n>=1

变换:

d(n) - d(n -1) = e(n - 1) = 6n

可以看出是一个等变数列,用累加法:

d(n) - d(n -1) =  6n

d(n -1) - d(n -2) =  6(n-1)

...............................

d(1) - d(0) = 6

累加:

d(n) - d(0) = 6n+6(n-1)+........+6(1) = 3n(n+1)

d(n) = 3n(n+1)+1

验算一下,没错,那么继续求c(n):

用同样方法 :

c(n) = c(n -1) + d(n - 1);

c(n) - c(n-1) = 3(n -1)n +1 = 3(n^2) -3n +1

c(n-1) - c(n-2) = 3(n -2)(n-1) +1 = 3((n-1)^2) -3(n-1) +1

.................................................

c(1) - c(0) = 3(1^2) - 3(1) +1

累加:

c(n)-c(0) = 3[n^2+(n-1)^2+.......+2^2+1^2]-3[n+(n-1)+...+2+1]+n

c(n)-c(0) = 1/2[2(n)^3+3(n)^2+n]-3/2[(n)^2+n]+n

c(n)-c(0) = (n)^3+3/2(n)^2+1/2 *(n)-3/2 *(n^2)-3/2 *n +n

c(n)-c(0) = n^3,已知 C(0) = 0

故得c(n) = n^3   n = 0,1,2.......