Skip to content

Commit 2d6a4ac

Browse files
committed
add collatz
1 parent 4b85b9f commit 2d6a4ac

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

collatz.py

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
"""
2+
This module, collatz.py, includes methods to work with the collatz or 3n+1
3+
conjecture. It contains three functions: collatz, dictionary, and orbit. More
4+
information is available in the docstrings of these fucntions.
5+
"""
6+
7+
def collatz(n):
8+
"If n is even, return n/2. If n is odd, return 3n+1."
9+
if n%2:
10+
return 3*n+1
11+
else:
12+
return n/2
13+
14+
def dictionary(maxval):
15+
"""Returns a tuple: a dictionary of numbers 1 to maxval as keys and their
16+
orbits as values, and the key of the highest value."""
17+
dict = {1:0}
18+
highest = 1
19+
for i in range(1, maxval+1):
20+
j = i
21+
steps = 0
22+
while True: #rely on break to exit loop
23+
if j not in dict:
24+
j = collatz(j)
25+
steps += 1
26+
else:
27+
dict[i] = dict[j] + steps
28+
if dict[i] > dict[highest]:
29+
highest = i
30+
break
31+
return dict, highest
32+
33+
def orbit(n):
34+
"Returns the number of steps for n to converge to 1."
35+
steps = 0
36+
while(n > 1):
37+
n = collatz(n)
38+
steps += 1
39+
return steps

nthPrime.py

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import math
2+
3+
def nthPrime(n):
4+
primes = [2]
5+
unchecked = 3
6+
while (len(primes) < n):
7+
couldBePrime = True
8+
threshold = math.ceil(math.sqrt(unchecked))
9+
for p in primes:
10+
if not unchecked%p: #if p divides unchecked
11+
couldBePrime = False #then it isn't prime
12+
break
13+
if p > threshold:
14+
break
15+
if couldBePrime:
16+
primes.append(unchecked)
17+
unchecked += 2
18+
return primes[n-1]

0 commit comments

Comments
 (0)