I want to enter numbers separated by spaces as input and store them in a list. I want to get all twin primes in that list as output. If there's no any twin primes in that inputted numbers I want to have an output "No any twin primes"
.
Twin Prime - two prime numbers whose difference is 2
So my code was like this:
lst = input()
test_list =[]
for ele in lst.split():
n_int = int(ele)
test_list.append(n_int)
def prime(x):
for k in range(2, x):
if x%k == 0:
return False
return True
diff = 0
for i in test_list:
for j in test_list:
if prime(i) and prime(j):
diff = abs(i-j)
if diff == 2:
print(i, j)
print("No any twin primes")
If I input a number series like 3 4 5 7 8
, I expect an output
3 5
5 7
but my output was
3 5
5 3
5 4
5 7
5 9
7 5
No any twin primes
If there's no any twin primes in the inputted list (2 3 7 9
) I get my expected output as
No any twin primes
.
CodePudding user response:
Changes made:
(1) Created a res
as a list which stores the Twin primes
(2) iteration of inner for loop is from i 1
to end
Code:-
lst = input("Enter the numbers: ")
test_list =[]
for ele in lst.split():
n_int = int(ele)
test_list.append(n_int)
def prime(x):
for k in range(2, x):
if x%k == 0:
return False
return True
diff = 0
res=[]
for i in range(len(test_list)):
for j in range(i 1,len(test_list)):
if prime(test_list[i]) and prime(test_list[j]):
diff = abs(test_list[i]-test_list[j])
if diff == 2:
res.append([test_list[i],test_list[j]])
if res:
for i,j in res:
print(i,j)
else:
print("No any twin primes")
Output:-
Enter the numbers: 3 4 5 7 8
3 5
5 7
Enter the numbers: 2 3 7 9
No any twin primes
CodePudding user response:
Here's my try:
def twinPrimes(iter):
primes = []
res = []
for i in iter:
for j in range(2, int(i/2) 1):
if i % j == 0:
break
else:
primes.append(i)
for i in range(len(primes)-1):
if primes[i 1] - 2 == primes[i]:
res.append((primes[i], primes[i 1]))
if res == []:
return "No any twin primes"
else:
return res
print(twinPrimes([3,5,7]))
You can also change the return to printing like:
def twinPrimes(iter):
primes = []
res = []
for i in iter:
for j in range(2, int(i/2) 1):
if i % j == 0:
break
else:
primes.append(i)
for i in range(len(primes)-1):
if primes[i 1] - 2 == primes[i]:
res.append((primes[i], primes[i 1]))
print(primes[i], primes[i 1])
if res == []:
print("No any twin primes")
Input: twinPrimes([3,5,7])
Output:
3 5
5 7
Input: twinPrimes([2,5,9])
Output:
No any twin primes