I want to change the for statement from C++ to Python, but I'm not sure.

Asked 2 years ago, Updated 2 years ago, 98 views

I am a student studying Python. I want to change the for statement below to Python in C, but I don't know how to change it.


for (int i = 3; (i*i) <= number; i += 2) {
      if (number % i == 0) return false;
   }

python for

2022-09-22 12:36

1 Answers

You cannot change the value of loop variable in python for loop. Therefore, the for loop you uploaded should be changed to when loop in Python. Alternatively, you need to change the conditional expression a little, such as i <= sqrt(number).

i = 3
while i*i<=number:
    if ....

    i+=2
from math import sqrt

for i in range(3, int(sqrt(number))+1):
    if ....


2022-09-22 12:36

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.