- A prime number is a natural number that is only divisible by 1 and by itself. Examples 1 2 3 5 7 11 13 17 19 …
- Using a for loop for checking if the number is divisible by a number from 2 to its square root.
- Running the for loop from 2 to the square root of the number.
- And then checking if the number is divisible by the numbers from 2 to its square root.
- Then, If the remainder is zero, that means it is divisible and hence not a prime number.
- If the loop runs till square root and none of the numbers divided it completely. So it is the Prime number.
- The code runs a loop from
i = 1
tosqrt(n)
in thefor
loop. - Within the loop, it performs a constant amount of work for each iteration: checking if
n % i == 0
and potentially incrementing thecount
variable. - Therefore, the time complexity of this code is
$O(sqrt(n))$ .
- The space complexity is determined by the memory used for variables.
- The code uses a few integer variables (
count
,i
, andn
), which occupy a constant amount of memory space. - Thus, the space complexity is O(1), indicating constant space usage.