+ 1

Check prime numbers from 1 to 100

public class Program { public static void main(String[] args) { for(int i=1;i<=100;i++) { boolean flag = true; for(int j=2;j<=i-1;j++) { if(i%j==0) { flag = false; break; } } if(flag == true) { System.out.print(i); System.out.print("\t"); } } } } //Please someone explain me at least one iteration

19th Jul 2020, 7:54 PM
Mayuri Vikram Deshmukh
6 odpowiedzi
+ 1
flag represents the truth of "i is prime" when it gets to the "if(flag == true)" line. A much clearer name would be iIsPrime. i%j will be true only if i is divisible by j. A prime number is a number i such that isn't divisible by any number j from 2 up to and including that number minus 1. The for(int j=2;...) loop updates flag to false only when i is proven to not be prime.
19th Jul 2020, 8:01 PM
Josh Greig
Josh Greig - avatar
+ 6
// if i is prime, print i. if(flag == true) { System.out.print(i); System.out.print("\t"); }
20th Jul 2020, 2:25 AM
Amit Kumar
Amit Kumar - avatar
+ 1
The opposite of what you said. // if i is prime, print i. if(flag == true) { System.out.print(i); System.out.print("\t"); }
19th Jul 2020, 9:03 PM
Josh Greig
Josh Greig - avatar
+ 1
Ex: 5 initially flag =true. Inner if i%j==0 never true.. (for 2,3,4). So flag won't change.. Outer if flag ==ture is ture, then prints 5. Ex: 4 In inner if, 4%2==0 true, flag set to false. Breaks loop. It will not print by outer if.
19th Jul 2020, 9:04 PM
Jayakrishna 🇮🇳
0
if condition telling that it is not a prime number right ?
19th Jul 2020, 8:12 PM
Mayuri Vikram Deshmukh
0
Thank you so much for the help !!
19th Jul 2020, 9:39 PM
Mayuri Vikram Deshmukh