[Tutor] Doubt in for loop
Steven D'Aprano
steve at pearwood.info
Thu Apr 4 03:53:41 CEST 2013
On 04/04/13 12:29, bessenkphilip wrote:
> Hi all,
>
> I'm having a doubt in the below program's 2n'd "for" loop.
>
>>>> for n in range(2, 10):
> ... for x in range(2, n):
> ... if n % x == 0:
> ... print n, 'equals', x, '*', n/x
> ... break
> ... else:
> ... # loop fell through without finding a factor
> ... print n, 'is a prime number'
> ...
> 2 is a prime number
> 3 is a prime number
> 4 equals 2 * 2
> 5 is a prime number
> 6 equals 2 * 3
> 7 is a prime number
> 8 equals 2 * 4
> 9 equals 3 * 3
>
> My doubt is that "will 'x' be always of value 2, if so why that for loop "for x in range(2, n):"
> i don't know how the first output , as If 2%2==0:(this satisfies the if loop as x =2) , so how the else part came to output i.e 2 is a prime number.
I'm sorry, I don't understand your question.
x is *not* always of value 2. You can see with the last line,
9 equals 3 * 3
x has value 3.
The outer loop just checks 2, 3, 4, ... 9 to see whether they are prime. The inner loop actually does the checking:
for x in range(2, n):
if n % x == 0:
print n, 'equals', x, '*', n/x
break
This tests whether n is divisible by 2, 3, 4, 5, 6, ... up to n-1. If n is divisible by any of those numbers, then n cannot be prime.
For example, with n = 9, the inner loop does this:
x = 2
Test if 2 is a factor: does 9/2 have remainder zero? No.
x = 3
Test if 3 is a factor: does 9/3 have remainder zero? Yes.
So 9 is not prime, and 9 = 3 * (9/3) = 3 * 3
If we test it with n = 35, the inner loop would do this:
x = 2
Test if 2 is a factor: does 35/2 have remainder zero? No.
x = 3
Test if 3 is a factor: does 35/3 have remainder zero? No.
x = 4
Test if 4 is a factor: does 35/4 have remainder zero? No.
x = 5
Test if 5 is a factor: does 35/5 have remainder zero? Yes.
So 35 is not prime, and 35 = 5 * (35/5) = 5 * 7
Notice that this does more work than necessary! Can you see what work it does that is unnecessary?
(Hint: what even numbers are prime?)
--
Steven
More information about the Tutor
mailing list