I'm newbie in Python. When I study in loop condition, I got code for prime number given below
i = 13
j = 2
while(j <= (i/j)):
if not(i%j): break
j = j + 1
if (j > i/j) : print i, " is prime"
Here I want logical to break while condition, if we want to find 13 is prime number or not we used loop range is 2 to 12.
Here they used only 3 loop because of the loop condition while(j <= (i/j))
.
The loop structure is
i ==> j while(j <= (i/j))
13 2 2<=6(13/2) true
13 3 3<=4(13/3) true
13 4 4<=3(13/4) false
My question is, how the condition 4<=3(13/4)
to satisfy the loop to check prime number?
I want maths logical any one help me the clear explanation.
The important thing here is to note that if ij = n, then at least one of i, j is less than or equal to sqrt(n). Therefore, we only need to check factors up to and including sqrt(n). So to test whether 25 is prime, we need to test factors up to 5. To test 23, we would need to loop and test 2, 3, and 4, and then when we get to 5 we notice that we're > sqrt(23) and break. The test j > i/j is the same test, since j > i/j implies that j^2 > i.
I'm not sure what the issue is exactly, because the provided code should correctly return that 13 is a prime number. I also tested it with 97, and it worked just fine.
I think you will want to pay special attention to the modulus operator when trying to solve for primes. With the modulus operator, you will divide the left side of the modulus with the right side and will be returned the remainder. If the remainder is 0, then you know the number is not prime because it divides evenly with some number.
Example:
In the provided code:
The while loop loops like the following (also note that without the decimal, the program will 'floor' the decimal to the lowest whole number):
Loop #1
Loop #2
Loop #3
To solve for a prime, you can follow these steps in their respective orders:
So you may get something like the following:
The latter is preferred because we don't have to hold onto and increment 'throwaway variable' (j in this case). We increment the for loop by 2 for this, and also because it reduces the amount of time your computer needs to work to find the answer since any even number is divisible by 2 (referring back to step #2). For small numbers, however, (e.g. 13) you won't notice the difference.
∆