Reputation: 756
In C we can check the value "i" less than the square root of n using this for loop
for (int i = 2; i * i <= n; i++)
I have used while loop as:
i = 2
while(i * i <= n):
i+=1
Can we able to do using for loop in python?
Upvotes: 2
Views: 3650
Reputation: 3407
It's pretty much the same.
In python, typical for
loop uses range(start, end, step)
function to get the indexing variable i
. It loop through i=start
to i=end-1
while incrementing i
by step
.
for i in range(start, end, step):
This is equivalent to C/C++/Java's
for (int i = start; i < end; i+=step)
Then, to stop by the square root of n
. You simply use what's below:
import math
for i in range(2, int((math.sqrt(n))+1):
Note that math.sqrt(n)
gives a float
. Then wrapping this in int
takes the floor
of the float
. And since for
loop stops at end-1
, we add 1 so this imitates the behavior requested by OP, i.e. i*i <= n
.
Some examples make this easier:
e.g. n=4
, then:
math.sqrt(n)=2.0
,int((math.sqrt(n))=2
,int((math.sqrt(n))+1=3
for i in range(2, 3)
will run the loop with i=2
and stop before i
reaches 3.Now, if n
is not perfect square:
e.g. n=10
,
math.sqrt(n)=3.16...
int((math.sqrt(n))=3
,int((math.sqrt(n))+1=4
for i in range(2, 4)
will run the loop with i=2
and i=3
and stop before i
reaches 4.While loop is exactly the same. Another way to write i*i
is i**2
in python.
i=2
while i**2 <= n:
i+=1
Upvotes: 2
Reputation: 1024
Its possible as @Tim mentioned, because in python for loop actually traverses through a range of values, but in C/C++ what we have is initialization;condition;increment
so that exact structure is not followed in python, instead its for x in range()
so the exact syntactical code is not possible, but you can achieve the same functionality (using while loop also or for loop as shown), as it is based on the features a language provides!
Hope it gives your answer!
Upvotes: 1