Skip to content

Instantly share code, notes, and snippets.

@obenn
Last active March 21, 2017 10:57
Show Gist options
  • Save obenn/3773b1530b230d05d3f2eaab905d9320 to your computer and use it in GitHub Desktop.
Save obenn/3773b1530b230d05d3f2eaab905d9320 to your computer and use it in GitHub Desktop.
Find the prime factorization of a given natural number.
# To implement: More efficient nextPrime method, clock to compute processing time.
# Oliver Benning, github.com/obenn
def nextPrime(divisor):
breakout = False
while not breakout:
divisor += 1
for i in range (divisor):
if (divisor) % (i + 1) == 0:
breakout = True
break;
return divisor;
def toString(divisor):
out = str(input)+" = "
for i in factors:
out += str(i) + "^" + str(factors[i])
if not i == divisor:
out += " * "
return(out)
input = int(input("What number would you like to prime factorize? \n"))
mod = input
divisor = 2
factors = {}
while mod > 1:
if mod % divisor == 0:
if divisor in factors.keys():
factors[divisor]+=1
else:
factors[divisor] = 1
mod = mod/divisor
continue;
divisor = nextPrime(divisor);
print(toString(divisor))
@LRexB
Copy link

LRexB commented Mar 21, 2017

An interesting task would be to come up with a mathematical proof that nextPrime() works.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment