Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert c++ for loop to Python?

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?

like image 508
maro Avatar asked Dec 08 '25 08:12

maro


1 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)
like image 73
DRPK Avatar answered Dec 09 '25 22:12

DRPK