日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

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

發(fā)布時(shí)間:2023/12/10 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 JOJ的2042面试题目的数学推导过程 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

JOJ的2042題目是一個(gè)程序理解題目,這個(gè)題目非常有意思,給出了下面一段C++源代碼,要求計(jì)算出最后的輸出結(jié)果,源代碼如下:

#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.

代碼就是上面那一段。

這個(gè)題目通過小數(shù)據(jù)計(jì)算可以看出規(guī)律:x=1, c = 1; x=2, c=8; x=3, c=27; x=4, c=64,于是可以猜測這段程序是用來計(jì)算x^3的。用計(jì)算器計(jì)算出987654321^3,提交上去就AC了。

這個(gè)題目是超級大牛SIYEE出的。但是為什么會(huì)得到這樣神奇的結(jié)果?有數(shù)學(xué)推導(dǎo)方法嗎?

有!而且是高中數(shù)學(xué)知識!這時(shí)候才知道高中數(shù)學(xué)是多么有用呵!

首先看這個(gè)程序:

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

這里c,d,e充當(dāng)了一個(gè)臨時(shí)寄存器角色,不要被賦值語句迷惑了,其實(shí)c,d,e都是數(shù)列

首先在草稿紙上列出前幾列:

x??0???1??? 2

c? 0?? 1??? 8

d ?1?? 7?? 19

e? 6?? 12? 18

?

然后在C語言描述中看:

(1)c的數(shù)列描述:

c(n) = 0;??? n = 0

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

(2)d的數(shù)列描述:

d(n) = 1;??? n = 0

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

(3)e的數(shù)列描述:

e(n) = 6(n+1)

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

計(jì)算d(n):

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

變換:

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

可以看出是一個(gè)等變數(shù)列,用累加法:

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

驗(yàn)算一下,沒錯(cuò),那么繼續(xù)求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.......

總結(jié)

以上是生活随笔為你收集整理的JOJ的2042面试题目的数学推导过程的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。