-2

I have it set so the user enters a max input and then the program figures out which numbers are prime and then prints it all to a file. But at the moment it only prints the closest prime number to the upper input. I need it to print 20 random numbers and put them on a file. Also with print (num) 20 times it can print 20 different outputs, but if I add print (num) 20 times it prints the same number 20 times

import random
#Always start at 2
lower = 2
#Take input from the user
upper = int(input("Enter maximum size for prime number to be: "))
for num in range(lower,upper + 1):
  if num > 1:
    #Prime numbers are greater than 1
    for i in range(2,num):
        if (num % i) == 0:
            break
        #End program if number is 0
        #Print results
    else:
        randomprimes =(num)
        primes =(random.choice(randomprimes))
        import sys
        former, sys.stdout = sys.stdout, open('Prime Number Generator Output.txt', 'w')
        print (primes)
        results, sys.stdout = sys.stdout, former
        results.close()
Ross Ridge
  • 35,323
  • 6
  • 64
  • 105

1 Answers1

2

random.choice from the random module returns a random item from a given iterable.

If you want 20 random items from a given list without repeating, use random.sample. (Thanks, Hugh Bothwell)

edit: Wouldn't normally do this, but here's a solution:

import random, math

upper = int(input("Enter maximum size for prime number to be: "))
primes = [x for x in range(2, upper) if x not in [j for i in range(2, math.ceil(math.sqrt(upper))) for j in range(i*2, upper, i)]]
with open("Prime Number Generator Output.txt", "w") as f:
    for prime in random.sample(primes, min(len(primes),20)):
        f.write(str(prime) + "\n")
L3viathan
  • 23,792
  • 2
  • 46
  • 64