I have made a Python program that can perform some prime number functions. For example, it can produce an endless output of sequential primes. I am looking for ways to make it faster and cleaner. When I was making it, I had a huge amount of trouble using generators, I don't know why, and what the problems were, because I made it long ago, so I had to stick to for
loops and class variables in the end.
class Maths():
prime = [2]
squares = []
primenum = 3
sqrnum = 1
fermat_number_true = 0
fermat_number_false = 1
def prime_generator(self):
while True:
if self.is_prime(self.primenum):
self.prime.append(self.primenum)
self.primenum += 2
return self.primenum - 2
self.primenum += 2
def is_prime(self, num):
for divisor in self.prime:
quotient = num / divisor
if quotient == int(quotient):
return False
return True
def square_generator(self):
while True:
self.sqrnum += 1
return (self.sqrnum - 1) * (self.sqrnum - 1)
def square_output(self):
while True:
print(self.square_generator())
def prime_output(self):
while True:
print(self.prime_generator())
def prime_on_enter(self):
while True:
input()
print(self.next_prime())
def square_on_enter(self):
while True:
input()
print(self.next_square())
def next_prime(self):
return self.prime_generator()
def next_square(self):
return self.square_generator()
def next_fermat(self):
while True:
prime = self.next_prime()
try:
while self.squares[-1] < prime:
self.squares.append(self.next_square())
except IndexError: self.squares.append(self.next_square())
if self.isfermat_alg2(prime):
self.fermat_number_true += 1
return True, prime
else:
self.fermat_number_false += 1
return False, prime
def next_fermatf(self):
true, num = self.next_fermat()
if true:
print("%d\t\t%f" % (num, (self.fermat_number_true / (self.fermat_number_false + self.fermat_number_true)) * 100))
else:
print("%d\tX\t%f" % (num, (self.fermat_number_true / (self.fermat_number_false + self.fermat_number_true)) * 100))
def fermat(self):
while True: self.next_fermatf()
def isfermat_alg1(self, num, squares):
for square in squares:
if num > square:
difference = num - square
if difference in squares:
return True
else:
return False
def isfermat_alg2(self, num):
return bool(num % 4 == 1)
def main(): mathsobj.prime_output()
mathsobj = Maths()
if __name__ == '__main__':
main()