日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

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

發布時間:2023/12/10 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 JOJ的2042面试题目的数学推导过程 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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面试题目的数学推导过程的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。