Home > database >  How can i iterate a for loop in python in the increaments of sum of another variable and iterator
How can i iterate a for loop in python in the increaments of sum of another variable and iterator

Time:03-22

i am trying to make a python program for "The Sieve Of Eratosthenes" but i am stuck at one place :

the c program i made 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

CodePudding user response:

I think you can do something like:

# rest of the code
# . 
# .
  j = i*i
  while j <=n:
    # resut of the code
    j  = i

CodePudding user response:

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

CodePudding user response:

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.

  • Related