I'm building a program to find prime numbers and I'm doing that by looping through numbers under 100 and I'm using two for loops to run through numbers and find if they're prime. My problem is that the second loops range is equal to the array of discovered prime numbers but I don't know how to add to that array as Python makes a clone variable when I append new numbers to the array meaning it only ever cycles through the second loop once.
def Primeadder():
primes = [1]
for i in range(100):
for j in range(len(primes)):
if j != 0:
continue
print(f"i = {i} and j = {j}")
print(len(primes))
if j != 0 and i%primes[j] == 0 and i not in primes:
primes.append(i)
print(primes)
Primeadder()
I've tried to use the numpy arrays but can't figure out how to install the library on visual studio. and I have no other ideas on how to fix this problem.
There are logic errors in your code
This is the correct code:
def Primeadder():
primes = []
for i in range(2, 100):
is_prime = True
for prime in primes:
if i % prime == 0:
is_prime = False
break
if is_prime:
primes.append(i)
print(primes)
This code starts at 2
because 1
is not a prime number, assumes each number is prime, checks for divisibility by known primes, and adds non-divisible numbers to the list of prime numbers. This way, it efficiently identifies prime numbers under 100
.
A prime is a natural number that has exactly two distinct natural number divisors: 1 and itself.