Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does (!(i % j)) mean not modulus of i and j = 0?

Tags:

c++

modulo

int main()
{
 int i,j;

 for (i=1; i<=25; i++)
 {
  for (j=2; j<= i/2; j++)
   if (!(i%j)) break;
  if (j>i/2) cout << i << "\n";
 }
 return 0;
}

This program (not written by me) outputs the prime numbers from 1 to 25, including 1 even though 1 isnt prime.

I am having trouble with this line: if (!(i%j)) break;

Does this say "not modulus of i and j = 0?

like image 775
Raptrex Avatar asked Dec 01 '22 06:12

Raptrex


2 Answers

!(i%j) is the same as (i%j)==0, or "i is divisible by j"

like image 93
Ned Batchelder Avatar answered Dec 09 '22 11:12

Ned Batchelder


The two following lines are essentially identical (as far as logic goes):

if (!(i%j))
if ((i % j) == 0)

The way I'd read the first line to make it clearer is "if there is not a remainder from i/j", ie, i is divisible by j.

like image 22
Matthew Scharley Avatar answered Dec 09 '22 11:12

Matthew Scharley