What is the difference between if(n==0) and if(!n) if n is a long long int?

After viewing the editorial for the Probem Musical Chairs , I tried it again on my ide.
The only difference in my code was that I changed if(n%i==0) to if(!n%i) and it gave wrong output for that. But if I use if(n%i==0) it is giving correct ouput and correct answer.
Can someone tell me what is happening?

#include"bits/stdc++.h"
#define ll long long int
using namespace std;
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    ll t;
    cin>>t;
    while(t--)
    {
        ll n;
        cin>>n;
        ll ans=0;
      
      n-=1;
      for(ll i=1;i*i<=n;i++)
      {
          if(!n%i)
          {
              ans++;
              if(i*i!=n)
                ans++;
          }
      }
      cout<<ans<<endl;

    }

    return 0;
}
if(n%i==0)   //first statement
if(!n%i)       //second statement

These two statements are different.
In that second statement (!n%i), ! operator is first inverting the value of n (here it is not the inversion of bits, just true to false or false to true) and then it modulo with i.
For eg: if the value of n is other than zero, it means n is true (1) and !n evaluates n to false(0), and if n is zero, it means n is false(0) and !n evaluates n to true(1).

You have to write second statement inside the bracket.

if(!(n%i))

Now when n%i==0, which acts as false, !(n%i) evaluates to true and then that if condition executes.
Now these two statements are equivalent.

if(n%i==0)   
if(!(n%i))       
5 Likes

thanks