Last active
August 11, 2020 17:51
-
-
Save sebastianv89/097fcebe592d4001c575495217958c81 to your computer and use it in GitHub Desktop.
Balancing numbers
This file contains 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
import math | |
N = 10000000 | |
def check_bm(n, r): | |
lhs = (n*(n-1))//2 | |
rhs = n*r + (r*(r+1))//2 | |
return lhs == rhs | |
def list_bm(): | |
for n in range(0, N): | |
d = 8*n*n + 1 | |
sqrtd = math.isqrt(d) | |
if sqrtd * sqrtd != d: | |
continue | |
r = (-2*n-1 + sqrtd) // 2 | |
if not check_bm(n, r): | |
print(f'n={n}; r={r}; oops...') | |
continue | |
print(f'n={n}; r={r}') | |
def check_ibm(n, r): | |
lhs = (n*(n+1))//2 | |
rhs = n*r + (r*(r+1))//2 | |
return lhs == rhs | |
def list_ibm(): | |
for n in range(0, N): | |
d = 8*n*n + 8*n + 1 | |
sqrtd = math.isqrt(d) | |
if sqrtd * sqrtd != d: | |
continue | |
r = (-2*n-1 + sqrtd) // 2 | |
if not check_ibm(n, r): | |
print(f'n={n}; r={r}; oops...') | |
continue | |
print(f'n={n}; r={r}') | |
if __name__ == '__main__': | |
print('balanced numbers (not including n)') | |
list_bm() | |
print('balanced numbers (including n)') | |
list_ibm() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment