Prime number

By Sudipchoudhury.myapplications, 10 months ago
  • Bookmark
1

I am trying to find list of prime numbers from a list of numbers. I am not getting correct output. Looks like the problem is happening with range in second for loop.


Kindly help to build with this login only. Let me know where to modify.



length = int(input('Enter the range: '))

l=[]

for i in range(length):

  l.append(int(input(f"Element at position {i} is: ")))

print(l)

prime=[]

count = 0

for j in l:

  for k in range(1,j+1):

    if (j%k==0):

      count+=1

  if (count==2):

    prime.append(j)

print(prime)


Output:


Enter the range: 3
Element at position 0 is: 10
Element at position 1 is: 7
Element at position 2 is: 3
[10, 7, 3]
[]


Python
1 Answer
0
Pritam Shinde

There is no need for a count. You can use the following code.



length = int(input('Enter the range: '))
l=[]

for i in range(length):
  l.append(int(input(f"Element at position {i} is: ")))

print(l)

primes = []

for j in l:
    if j > 1:  
        for i in range(2,j):  
                if (j % i) == 0:  
                    break  
        else:  
            primes.append(j)  
         
print(primes)

Output:


Enter the range: 3

Element at position 0 is: 10

Element at position 1 is: 7

Element at position 2 is: 3

[10, 7, 3]

[7, 3]

in prime no, only 1 and self no will divide, so skip 1 and self no and check for others

– Pritam Shinde Jul 26, 2021 at 5:06 PM

Your Answer

Webinars

More webinars

Related Discussions

Running random forest algorithm with one variable

View More