Prime and Mersenne Prime Testers

I’m teaching my son python and we were talking about primes. We thought we could write a program for that but he and I had different ideas for how to do it. So we had a code-off competition. It was the first program he ever wrote. We both worte successful programs so I say we both win. Here’s mine:

[python]
while True:
print("What number do you want to test?")
zab = input()
if zab.isdigit():
zed = round(int(zab)**(1/2)) + 1
q = 0
if int(zab) < 2:
q += 1
elif int(zab) > 2:
for i in range(2,int(zed)):
if int(zab) % i == 0:
q += 1
if q > 0:
break
if q == 0:
print(str(zab) + " is prime")
else:
print(str(zab) + " is not prime")
[/python]

Afterwards he was telling me about mersenne primes and again I thought we could make a program for that, so we took my prime tester and turned it into a simple mersenne prime tester.

[python]primes = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
127, 131, 137, 139, 149, 151, 157, 163, 167, 173,
179, 181, 191, 193, 197, 199] #all primes up to 200

#while True:

for n in primes:
x = (2 ** n) – 1

if str(x).isdigit():
zed = round(int(x)**(1/2)) + 1
q = 0
if int(x) < 2:
q += 1
elif int(x) > 2:
for i in range(2,int(zed)):
if int(x) % i == 0:
q += 1
if q > 0:
break
if q == 0:
print(str(x) + ", ", end=”)[/python]

Simple Clock

My youngest son loves clocks so together we made a simple program that prints out the time, waits a minute, then prints out the next time again each minute.

[python]
import time

print("What time is it?")

string = input()

dot = string.find(":")

hour = string[:dot]
minute = string[dot + 1:]

while True:
time.sleep(60)
if int(minute) < 59:
minute = int(minute) + 1

elif int(minute) == 59:
minute = 0
if int(hour) < 11:
hour = int(hour) + 1
else:
hour = 1
if len(str(hour)) == 1:
hour = "0" + str(hour)

if len(str(minute)) == 1:
minute = "0" + str(minute)

print(str(hour) + ":" + str(minute))
[/python]

Binary converter

So here is my super simple binary converter. It is the first program I wrote by myself. I was watching a video about basic computer programming and thought, “I could write a program to do that!” So I did. Looking at it now it seems silly both in concept and execution. However it was my first so I’m not going to fix it but instead publish it because completing it gave me confidence.