# 2020q3 Homework5 (quiz5) ## 測驗 `1`: divop 當被除數 `slot` 為偶數:計算 $divop(orig / D1, slot)$ 為奇數:計算 $divop(orig / D1, (slot + D2) / 2) + divop(前者, slot)$ 可知每次遞迴 `divop` 的 `orig` 應越來越小,而除數 `slot` 則根據其奇偶會補上 `D2`, 可判斷應為 `1` 若將奇數的程式化為數學式,假設被除數為 A, 除數為 B: $\dfrac{A}{B} = \dfrac{A/D1}{(B+1)/2} + \dfrac{\dfrac{A/D1}{(B+1)/2}}{B} = \dfrac{A/D1}{(B+1)/2}(1 + \dfrac{1}{B}) = \dfrac{A/D1}{(B+1)/2}(\dfrac{B+1}{B})$ $= \dfrac{A}{B}(\dfrac{2}{D1})$,因此 `D1` 等於 `2`。 ## 測驗 `2`: LeetCode 829. [Consecutive Numbers Sum](https://leetcode.com/problems/consecutive-numbers-sum/) 給定一個正整數 N,問 N 能寫成多少種連續正整數之和,例如 $9 = 4 + 5 = 2 + 3 + 4$ 若將此問題化為等差數列則會變成 $N = a + (a+1) + ... + (a+k-1) = ka + \dfrac{(k-1)k}{2}$ $ka = N - \dfrac{(k-1)k}{2}$ ```cpp= int consecutiveNumbersSum(int N) { if (N < 1) return 0; int ret = 1; int x = N; for (int i = 2; i < x; i++) { x += ZZZ; if (x % i == 0) ret++; } return ret; } ``` 此題關鍵在於知道 k 的範圍後,根據 k 的變化去修正整數 `x` k = 2 時, $2a = N -\dfrac{(2-1)2}{2} = N-1$ k = 3 時, $3a = N -\dfrac{(3-1)3}{2} = N-1-2$ k = 4 時, $4a = N -\dfrac{(4-1)4}{2} = N-1-2-3$ 相當於在每一次的迴圈中,都將前一個迴圈中的整數 x ($=ka$) 再減去 (k-1),故 `ZZZ` 等於 `1-i`。 Line 9 則是判斷在該 k 值下的 a 是否為整數,是的話表示該等差數列存在。 :::warning TODO: i < x ::: ###### tags: `linux2020`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up