1

I am new to Python so please excuse me if this is a very obvious questions, how do I write a statement like this in Python

for (int i=p*2; i<=n; i += p)
for i in range(p*2, n)

but then how does it increment?

0

3 Answers 3

4
for i in range(p*2, n + 1, p): # range(inclusive start, non inclusive end, step)
Sign up to request clarification or add additional context in comments.

Comments

4

range generates a sequence of numbers - a range. For example, range(0,5) is equivalent to [0, 1, 2, 3, 4]. It's signature is range(start, stop, stride), which in C would be

for (int i=start; i<stop; i+=stride)

So you should iterate as

for i in range(p*2, n+1, p):
    ...

Comments

1

if you look up the range function you will notice that it actually can take three arguments. The third value is the amount to increment by, which is 1 by default. Just change to

range(p*2, n, p)

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.