Skip to content

Instantly share code, notes, and snippets.

@Mithrandir0x
Last active December 19, 2015 08:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mithrandir0x/5925538 to your computer and use it in GitHub Desktop.
Save Mithrandir0x/5925538 to your computer and use it in GitHub Desktop.
Mathematic Algorithms
def fibonacci(n):
"""A Fibonacci generator"""
x_1, x = 1, 1
while ( x < n ):
yield x
x_1, x = x, x + x_1
def erastothenes_sieve(n):
"""Get all the prime numbers below 'n'"""
sqrtN = math.sqrt(n)
A = [i for i in range(2, n + 1)]
def mark_as_non_prime_value_at(i):
A[i] = -1
def only_prime_numbers():
return [ A[i] for i in range(0, len(A)) if A[i] != -1 ]
[ mark_as_non_prime_value_at(j) \
for i in xrange(A.index(int(sqrtN + 1)) + 1) \
for j in xrange(i, len(A), A[i]) \
if A[i] != A[j] and A[j] % A[i] == 0 ]
return only_prime_numbers()
def is_palindrome(x):
x = str(x)
k = len(x)
for i in xrange(k/2):
if x[i] != x[k-i-1]:
return False
return True
def triangular_number(n):
"""Return the 'n' Triangular Number"""
return (n * (n+1)) * 0.5
def triangular_numbers(n):
"""Generate a list of 'n' Triangular Numbers"""
i = 1
k = 0
while k < n:
yield i + k
k += 1
i += k
def next_triangular_number():
"""Triangular Number Generator"""
i = 1
k = 0
while True:
yield i + k
k += 1
i += k
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment