How to convert c++ for loop to Python?

Viewed 1565

I wrote a code in C++ and would like to convert it to Python3. How to do that?

int N = 1000
for (p=2; p*p<=N; p++)
    for (w=p*p; w<=N; w=w+p)

I tried to change the first for loop to:

for p in range(2,N**0.5+1):

But it doesn't work - TypeError: 'float' object cannot be interpreted as an integer

And what about the second for loop?

2 Answers

Try This ( in python You should do that with while ):

N = 1000
p = 2

while p*p <= N:

    p = p + 1
    w = p*p
    print(p)

    while w <= N:
        w = w + p
        print(w)

UPDATE :

The reason that you get the error "TypeError: 'float' object cannot be interpreted as an integer" is that the "range" function expects "integers" as arguments, whereas "N ** 0.5" is of type float, so is "N ** 0.5+1". To resolve this issue you can simply use "int" function to the conversion from float to integer. The following code is what you are looking for:

N = 1000
for p in range(2, int(N ** 0.5) + 1, 1):
    for w in range(p * p, N + 1, p):
        print(p, w)
int N = 1000
for (p=2; p*p<=N; p++)
    for (w=p*p; w<=N; w=w+p)

In Python, the range() function takes in 3 parameters: int start, int stop, int step. Since your second argument is N**0.5, with 0.5 of type float, the result of that calculation is interpreted as of type float.

My suggestion is:

from math import sqrt
n = 1000
m = int(sqrt(n))
for p in range(2,m):
  for w in range(p*p, n+1, p)
    print(p,w)

Does that solve your problem?

Related