FOR i:=2 TO 20 DO BEGIN
prime:= TRUE;
FOR j:=2 TO i-1 DO BEGIN
IF i MOD j=0 THEN
prime:=FALSE;
END;
IF prime=TRUE THEN
MESSAGE(Text1000,i) ;
END;
i want to run the coding of prime numbers on the form itself.
please tell me whether my code is right or wrong, it showing 2 as a prime number, but whn i dry
run it for i:=2 it should not include 2 as a prime number. Please correct me.
0
Comments
the problem here is that in the case of 2, the second loop ( the one with the J variable ) will never execute. Just look at it, it'll read "FOR J := 2 to 1 DO", and that won't do anything.
Definition of prime: A natural number is called a prime number (or a prime) if it is bigger than one and has no divisors other than 1 and itself. [source=Wikipedia]
Which means that by definition 2 is a prime.
So there is nothing wrong with your code, only with your interpretation
If you do not want to see 2, then just add a check that when i is equal to 2, it shouldn't show the message.
|To-Increase|
When i know according to my logic , it shouldnt print 2 as a pime number. Any one can clear my doubt?
RIS Plus, LLC
Just look at it line by line. If the 2nd loop doesn't execute, how will you ever set "prime" equal to false? The debugger is an excellent tool for figuring out these types of issues.
second loop is from 2 until the first loops current number -1.
If the first loop is at number 2, the second loop won't trigger. (because its for 2 to 2-1)
MBerger pointed out that the second loop will never trigger with the number 2, and did not mean never at all.
That's why this piece of code is very good for prime numbers, even tough it means that the code won't run trough every loop.
|To-Increase|
this is my final code and its working:
FOR i:=2 TO 20 DO BEGIN
IF i=2 THEN BEGIN
MESSAGE(Text1000,i)
END
ELSE
BEGIN
prime:= TRUE;
FOR j:=2 TO i-1 DO BEGIN
IF i MOD j=0 THEN
prime:=FALSE;
END;
IF prime=TRUE THEN
MESSAGE(Text1000,i) ;
END;
END;