+ 1

Can somebody help me to understand this code line by line?

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SoloLearn { class Program { static void Main(string[] args) { int i, j; for (i=2; i<100; i++) { for (j=2; j <= (i/j); j++) if ((i % j) == 0) break; if (j > (i/j)) Console.WriteLine("{0} is prime", i); } } } }

2nd May 2017, 1:33 PM
Kev
Kev - avatar
6 Answers
+ 11
@Fuyuka C#
2nd May 2017, 1:46 PM
Complex
Complex - avatar
+ 10
using (thingy things); //Use some modules to make the code work namespace Sololearn { //make a namespace class Program { //Make a class called program static void main(String[] args) { //Main function, entry point if the code int i, j; //Declare an empty integer i and j for(i = 2; i < 100; i++) //integer i is now has the value 2 and it iterates 98 times. { for(j = 2; j <= (i/j); j++) //j has the value of 2 j is smaller or equal than i divided by j. if((i % 2) == 0) break; //Stop the loop if you divide i by 2 and the remainder is 0 if(j > (i/j)) //If j is larger than i divided by j... Console.WriteLine("{0} is prime", i); //Print the value of i and "is prime" } } } Hope this helps, Good luck, and happy coding
2nd May 2017, 1:46 PM
Complex
Complex - avatar
+ 10
What language is this ?
2nd May 2017, 1:46 PM
Fuyuka Ayumi(ć†ŹèŠ±)
+ 10
@Kev Just remember Operator Precedence If doing Math expressions in loop or conditional try adding parentheses
2nd May 2017, 1:59 PM
Complex
Complex - avatar
+ 2
well first for is obvious it counts from 2 to 100 in order to print primes between. And about the second for as it says until j<=i/j(which means until j^2 <= i) check if i is divisible by j so if its true it means our number is not prime since it is divisble by a number other than itself and 1. and the reason for j^2 <= i is that for it is not needed to check all numbers till i-1 since if the number is not prime it can devided by a number which is <= sqare(i).
2nd May 2017, 1:53 PM
Saeed Tafazzol
Saeed Tafazzol - avatar
+ 2
ahh ok ty all i had some Problems with if (j=2; j <=(i/j); j++)
2nd May 2017, 1:59 PM
Kev
Kev - avatar