Skip to content

Instantly share code, notes, and snippets.

@sebastianv89
Last active August 11, 2020 17:51
Show Gist options
  • Save sebastianv89/097fcebe592d4001c575495217958c81 to your computer and use it in GitHub Desktop.
Save sebastianv89/097fcebe592d4001c575495217958c81 to your computer and use it in GitHub Desktop.
Balancing numbers
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