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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With