I am trying to get the first N prime numbers in the following way:

    def n_primes(self, num):
        primes = [2]
        p = sp.local("p", 1)
        i = sp.local("i", 3)
        n = sp.local("n", num)
        c = sp.local("c", 0)

        sp.while p.value < n.value:
            sp.while (i.value % primes[c.value] != 0) & (primes[c.value] * primes[c.value] <= i.value):
                c.value += 1

            sp.if (i.value % primes[c.value] != 0):
                p.value += 1

            c.value = 0

            i.value += 2

        self.data.last_prime = primes[n.value - 1]

but I get the error: "Error: list indices must be integer, not Expr" on the second while loop (by testing this on smartpy.io/dev). I've tried not using smartpy local variables, but then it doesn't work properly and it gets stuck in an infinite loop for some reason. I have also tried using a for loop instead of a while ("for x in primes") but then I get a "declaration error, x variable escapes its scope", and also couldn't make it work with the conditions that I wanted.

Is there any way of telling the program that the expression used as the list index is an integer?

Note: The equivalent of this program works fine in normal python.

1 Answer 1


In Michelson you cannot access list items by index, you need to iterate over it.

You should do something like:

sp.for prim in primes:
  sp.if p.value < n.value:
    # stuff...


  • I appreciate the response, but doing this, I only get one iteration of the for loop and end up with [2, 3] in the list no matter the value of num. I could try using that for loop after the sp.while p.value < n.value: but then I'm not sure how to use the two conditions (of the second while) in conjunction with the loop so the program doesn't go through the entire list.
    – ralex21
    Jun 22, 2021 at 19:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.