I am having issues with trying to figure out where to start on generating a table that will look like this:
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 211 223 227 229
This is my code thus far that solves for the first 1000 primes, but I'm unsure how to get in a 10x100 table.
Code:
def is_prime(number):
for i in range(2,number):
if ((number % i) == 0):
return False
return True
def main():
for value in range(2, 7920):
if ( is_prime(value) ):
print(value, end='\t')
main()
Just keep track of how many you have printed on the current line.
def main():
count = 0
for value in range(2, 7920):
if (is_prime(value)):
print(value, end='\t')
count += 1
if count % 10 == 0:
print()
The easiest approach is to accumulate each row in a list. Whenever the list reaches ten elements, display that row in a nicely formatted way:
def is_prime(number):
for i in range(2,number):
if ((number % i) == 0):
return False
return True
def display_row(row):
print(''.join(format(value, '7d') for value in row))
def main():
row = []
for value in range(2, 7920):
if ( is_prime(value) ):
row.append(value)
if len(row) == 10:
display_row(row)
row = []
display_row(row)
main()
The logic for display_row() says to take every value and format it as a decimal, padding with spaces as necessary to fill exactly 7 spaces and then join those together in a single string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With