'How can I iterate a for loop in Python in the increments of sum of another variable and iterator
I am trying to make a python program for "The Sieve Of Eratosthenes" but I am stuck at one place.
The c program I wrote looks something like this :
for (i = 2; i <= n; i++)
{
if (prime[i] == 0)
{
for (j = i*i; j <= n; j += i)
{
prime[j] = 1;
}
}
}
How will I write the code for for(j=i*i;j<=n;j+=i) in Python?
As by default python increment the iterator by 1
Solution 1:[1]
You code could be rewritten like this
for i in range(2,n+1, 1):
if prime[i]==0:
for j in range(i*i, n+1, i):
prime[j]=1
The range function takes upto 3 values, the first is the starting value, the second is the ending value (exclusive) and the third is the amount to step each time.
The full semantics of range can be found here
Solution 2:[2]
I think you can do something like:
# rest of the code
# .
# .
j = i*i
while j <=n:
# resut of the code
j += i
Solution 3:[3]
Im a little confused because I have no idea what the syntax of C is, but I assume you want to do something along the lines of
for i in range(n): # run from 0 to the value of n (int)
if prime[i] == 0: # assuming prime is a list
for j in range(i**2): # runs from 0 to the value of i squared
prime[j] = 1
This code should work in terms of syntax and actually running (assuming you have defined prime and n somewhere), but you may have to do some tweaking to the for loops to make it acheive the desired effect. Remember, a for loop in that way of construction will have a temporary variable called i that is 0, and as long as the value of i is less than the value of n, the code will run and each time i will increment itself by one. If you want to change it a bit, you could use range(start, stop, step), in which the start is the starting value of i (not 0), and stop is the stopping value (n). step is also the amount in which the variable of i will increment itself by each time the code loops.
I hope this helps. please ask any questions you have.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alex |
| Solution 2 | Amirhossein Kiani |
| Solution 3 | KingTasaz |
