int modPow(long long x, long long y)
{
if (y == 0)
return 1;
long long p = modPow(x, y / 2);
p = (p * p) % mod;
return y % 2 ? (p * (x % mod)) % mod : p;
}
這題的重點是實現pow with mod.
class Solution {
int mod = 1e9 + 7;
public:
int modPow(long long x, long long y)
{
if (y == 0)
return 1;
long long p = modPow(x, y / 2);
p = (p * p) % mod;
return y % 2 ? (p * (x % mod)) % mod : p;
}
int minNonZeroProduct(int p) {
long long cnt = ((1ll << p) - 1) % mod;
return cnt * modPow(cnt - 1, cnt / 2) % mod;
}
};
/*
p = 4, 2^4 - 1 = 15 -> 0b1111
0001, 0010, 0011, 0100, 0101, 0110, 0111, 1000, 1001, 1010, 1011, 1100, 1101, 1110, 1111
|_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|______| 0001, 1110
|_____|_____|_____|_____|_____|_____|_____|_____|_____| 0001, 1110
|_____|_____|_____|_____|_____|_____|_____| 0001, 1110
|_____|_____|_____|_____|_____| 0001, 1110
|_____|_____|_____| 0001, 1110
|_____| 0001, 1110
(2^p - 1) * (2^p - 2) / 2 * (2^p - 2)
(2^p - 1) * pow(2^p - 2, (2^p - 1) / 2)
pow(14, 8) = (14 * 14) * (14 * 14) * (14 * 14) * (14 * 14)
--------------------- ---------------------
= pow(14, 4) * pow(14, 4)
*/
給你n個硬幣,試問可以排出幾階的樓梯形狀。例如n=8只可以排出3階樓梯。
解題思路
記得某種解題方法是,如果沒有好的想法,就先想一下special case。
這邊的special case是,如果給你的n剛好可以排出staircase則會是幾階?
因為staircase的總數為(1+2+3+…)的等差級數所以可以用下面的公式
\[ n = {(1+m)*m \over 2} = {{1 \over 2}m^2 + {1 \over 2}m} \]
所以要得到幾階的m就是解一元二次方程式。
\[ x = {-b \pm \sqrt{b^2-4ac} \over 2a}. \]
所以
\[ m = {-{1 \over 2} + \sqrt{{1 \over 2}^2 + 2 *n}} \]
程式碼:
int arrangeCoins(int n) {
return sqrt(0.25 + 2.0 * n) - 0.5;
}
leetcode
刷題
or
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up
Syntax | Example | Reference | |
---|---|---|---|
# Header | Header | 基本排版 | |
- Unordered List |
|
||
1. Ordered List |
|
||
- [ ] Todo List |
|
||
> Blockquote | Blockquote |
||
**Bold font** | Bold font | ||
*Italics font* | Italics font | ||
~~Strikethrough~~ | |||
19^th^ | 19th | ||
H~2~O | H2O | ||
++Inserted text++ | Inserted text | ||
==Marked text== | Marked text | ||
[link text](https:// "title") | Link | ||
 | Image | ||
`Code` | Code |
在筆記中貼入程式碼 | |
```javascript var i = 0; ``` |
|
||
:smile: | ![]() |
Emoji list | |
{%youtube youtube_id %} | Externals | ||
$L^aT_eX$ | LaTeX | ||
:::info This is a alert area. ::: |
This is a alert area. |
On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?
Please give us some advice and help us improve HackMD.
Syncing