+ 5
Prime Numbers Within An array
I am making a code that prints square and prime numbers within an array. Does anyone know how to do this. (I am using a for loop and language is Python) code: nums = [8383,8392,101,3929,9999,53849,7373,10,666373] try: x=1 print("full array:") for i in range(len(nums)): x=x+1 print(nums[x]) print("primes:") except: print(" ")
1 Antwort
+ 2
For primes this should work:
nums = [8383, 8392, 101, 3929, 9999, 53849, 7373, 10, 666373]
def is_prime(n):
if n == 1: # 1 is not a prime
return False
elif n == 2:
return True # 2 is a prime
else:
for i in range (2, n // 2):
if n % i == 0:
return False # not a prime if divisible by i
return True # n is prime number
print('full array:')
for n in nums:
print(n)
print()
print('primes:')
for n in nums:
if is_prime(n):
print(n)