# what I'm doing wrong?? i want to find prime numbers in matrix and add in a new list (PYTHON)

lst1=[ ]

lst2=[ ]

import numpy as np

n=3

m=4

mat=np.random.randint(10, size=(n,m))

print(mat) for i in range(n):

for j in range(m):

for a in range(2, mat[i][j]):

if mat[i][j]%a!=0:

lst2.append(mat[i][j])

break

else:

lst1.append(mat[i][j])

print(lst1)

answered Apr 9, 2022 by (88,520 points)

First of all, you should create meaningful variable names. For instance, what are lst1 and lst2? Wouldn't it make more sense to call them primes and compounds?

Your test for primes is logically incorrect. What you do is this:

1. Test if a number can be divided without any remainder by a
2. If there is a remainder, you put it into list1 (primes?, compound numbers?) and stop the loop
3. If there is no reminder, you put it into list2, but you keep doing your innermost loop so potentially you would put the same number in the other list as well or even the same list again.

A correct (but not the most efficient) way to test for prime would be like this (your loop conditions are correct: for a in range(2, mat[i][j]))

1. If the number in test can be divided by any of the values of a, then it is a compound number. Put it in the compounds list and terminate the innermost loop.
2. If you finish the innermost loop without putting your a into the compounds list, then it had no whole dividers, hence it is a prime and should go into the primes list.

I hope this helps.

Good luck with the implementation!