Created
July 1, 2020 09:03
-
-
Save alldroll/922629165cd758b75460e0840454cf93 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // a1 + a2 + a3 + .. + an = n * (a1 + an) / 2 | |
| // 1 + 2 + 3 + 4 + 5 | |
| // 5 * (1 + 5) / 2 = 10 | |
| func arrangeCoins(n int) int { | |
| i, j := 1, n + 1 | |
| for i < j { | |
| h := int(uint64(i + j) >> 1) | |
| sum := (h * (1 + h)) / 2 | |
| if sum < n { | |
| i = h + 1 | |
| } else { | |
| j = h | |
| } | |
| } | |
| if sum := (i * (1 + i)) / 2; sum > n { | |
| i-- | |
| } | |
| return i | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment