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.......
- JOJ的2042面试题目的数学推导过程
- JOJ的2042面试题目的数学推导过程
- 惯性力的数学推导
- 惯性力的数学推导
- lstm的数学推导
- lstm的数学推导
- Google的面试题目(数学部分)
- 反向传播算法BP的数学推导过程以及示例
- KMP 算法的数学推导
- svm的数学推导原理
- logistic回归的数学推导
- 投射投影过程数学推导
- BP的详细推导过程
- Lucene打分公式的数学推导
- 梯度下降法的数学推导
- 十七、逻辑回归公式的数学推导
- Lucene打分公式的数学推导
- SMO算法的极简数学推导
- vista服务管理
- 少的力量(Power of Less)
- pku 3735 Training little cats (矩阵幂乘)
- document.forms[0]
- 系统分析员--论文应试准备
- JOJ的2042面试题目的数学推导过程
- Office Software Protection Platform
- 表格的属性
- Log4j中将控制台出现的异常信息完整的记录到日志文件
- COM组件
- C#调用RAR压缩与解压
- 解印度CMM模式困境 提供中国软件发展新思路
- Internet tcp协议传输数据时丢包的解决方法
- 对几个 T-SQL 特有的常用语法点的总结