Finding primes in a list of numbers?

Hi, I’m trying this python script to get it to run through a list of input values x, and then output a true or false for each number in the input list.

I started with the code provided in this topic:

I changed the code to this:

def primes(n):
    results = []
    if n <= 1: results.append("False")
    if n>1:
        for i in range(2, n//2):
            if(n % i) == 0:
    return results

a = primes(x)

It does output a list, but I’m not getting the correct answers, is there anything I’m missing? I’ve been looking at this for over three hours and my coding isn’t strong so I throw in the towel :smiley:

Anyone knows why my adaptation doesn’t work?

Here is an example file with a numbered list and output: (7.5 KB)

This won’t help you right now, but G2 shows primality for all integers displayed in panels and has ways to extract all integer factors.


In your code you are building an array “results” for each single number to test.
Your number is prime or not, a single output is enough.
(For your 421 inputs you are getting 423 outputs…)

Also, normally you would build a list of prime numbers iteratively, once, save the list, and use that same list to test all your input numbers.
Instead, for every of your number “n”, this code is iterating n/2 times… totally not optimized:

def IsPrime(n):
    if n<1: return("False")
    if n==1:return ("True")
    if n>1:
        for i in range(2, n//2+1):
            if(n % i) == 0:

a = IsPrime(x)
1 Like

IAC on food4Rhino has a couple prime components.


Wow, that IAC component did it! With a little change I could make the Python script work as well. Need to declare n = int(n)

I did google on food4rhino and ‘prime’ but it didn’t show me this one. Wow, great tip, also way faster than doing it in Python (1 sec in Python equals around 100ms in the IAC component). Thanks a lot, super valuable tip.

1 Like

There are many Python examples

p = []
for num in range(s, e + 1):
   # all prime numbers are greater than 1
   if num > 1:
       for i in range(2, num):
           if (num % i) == 0:

find prime (6.6 KB)