Created
April 30, 2016 12:15
-
-
Save fujidig/3e47e57a41b154aaea757a0805bf3442 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
| # Babylonian method | |
| def isqrt(n) | |
| return 0 if n == 0 | |
| s, t = 1, n | |
| while s < t | |
| s *= 2 | |
| t /= 2 | |
| end | |
| begin | |
| t = s | |
| s = (n / s + s) / 2 | |
| end while s < t | |
| t | |
| end | |
| def triangular(n) | |
| n * (n + 1) / 2 | |
| end | |
| # x (x + 1) / 2 <= n を変形すると | |
| # (2x + 1)^2 <= 8n + 1 | |
| def triangular_inv(n) | |
| a = isqrt(8 * n + 1) | |
| if a % 2 == 0 | |
| (a - 2) / 2 | |
| else | |
| (a - 1) / 2 | |
| end | |
| end | |
| def istriangular(n) | |
| triangular(triangular_inv(n)) == n | |
| end | |
| def issquare(n) | |
| isqrt(n)**2 == n | |
| end | |
| 1000.times do |i| | |
| [1, -1].each do |a| | |
| n = 2 ** i + a | |
| if istriangular(n) | |
| puts "#{n} is triangular" | |
| end | |
| if issquare(n) | |
| puts "#{n} is square" | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment