samedi 27 février 2016

For Loop result doesn't make sense to me

So I had the following code snippet on a quiz:

int a = 120;
int b = 90;
int n1 = Math.abs(a);
int n2 = Math.abs(b);
int result = 1;

for (int k = 1; k <= n1 && k <= n2; k++) 
{
   if (n1 % k == 0 && n2 % k == 0) 
   {
      result = k;
   }
}
System.out.println(result);

The output is 30 and I'm not sure why. As far as I can see, wouldn't the loop keep running until the counter broke 90 (90 being the absolute value of n2)? That would make result = 90. Or is there just something I'm not quite understanding?

Aucun commentaire:

Enregistrer un commentaire