0

I'm making a program that changes the value of n (in the equation of E = n^2 + n + 5) and predicts the probability that E will be prime. Here is my code:

n = 0
t = 0
p = 0
while 3 > 2:
  nn = n*n
  E = nn + n + 5
  n = n + 1
  if E > 1:
    for i in range(2, E):
        if((E % i) == 0):
          print(E, "is not prime when n =", n)
        else:
          print("Found a prime!", E, "when n =", n)
  t = t + 1
  print(t)
  if(t >= 50):
      break

fraction = p/t
print(p)
print(t)
percent_int = fraction*100
percent = int(percent_int)
print("The rounded probability of getting a prime number is:", percent_int, "%")

However, the program isnt working. It always says that the probability of getting a prime is 0%, when I know that it isnt (n=1 produces a prime number).

RtHAitP30D
  • 306
  • 3
  • 6
  • 19

1 Answers1

1
for i in range(2, E):
    if((E % i) == 0):
      print(E, "is not prime when n =", n)
    else:
      print("Found a prime!", E, "when n =", n)

Should be (since you don't know if E is prime until you try all the integers)

for i in range(2, E):
        if((E % i) == 0):
          print(E, "is not prime when n =", n)
          break
else:
    print("Found a prime!", E, "when n =", n)
    p += 1  # you also need to incrment p

However, the program can be simplified to the following alternative

from math import sqrt; from itertools import count, islice

def is_prime(n):
    " checks if input is prime"
    # Code from https://stackoverflow.com/questions/4114167/checking-if-a-number-is-a-prime-number-in-python)
    return n > 1 and all(n%i for i in islice(count(2), int(sqrt(n)-1)))

def calc_E(n):
  " converts n to your e value"
  return n*n + n + 5

# Counts the number of primes found for input n in the range 0 to 50.
p = sum(1 if is_prime(calc_E(n)) else 0 for n in range(51))
t = len(range(51))
print(p)
print(t)

percent_int = fraction*100
percent = int(percent_int)
print("The rounded probability of getting a prime number is:", percent_int, "%")
DarrylG
  • 16,732
  • 2
  • 17
  • 23