Chef and walk - WA- RECNDNUM

#include <bits/stdc++.h>
using namespace std;
unsigned long long fun(unsigned long long k){
    unsigned long  long x = 1000000007;
    return ((k*k)%x + k)%x;
}
int main() {
	// your code goes here
	int t;
	cin>>t;
	unsigned long long x = 1000000007;
	while(t>0){
	    t--;
	    unsigned long long n,k;
	    cin>>n>>k;
	    unsigned long long ans = 0;
	    if(n == 0)
	        ans = fun(k-1);//k(k-1)

	   else if(k %2 != 0)
	   {
	       ans = ((fun(n+(k/2) )%x) - n)%x;    //(n+k/2)(n+k/2 + 1)
	   }
	   else{
	       ans = (fun(n+(k/2)-1)%x + n%x)%x;     //(n+k/2-`1)(n+k/2)
	   }    
	   cout<<ans<<endl;
	}
	return 0;
}

what is wrong with this code?
i am getting WA for large numbers…

Question Link:

try ((k%x)(k%x) )%x)instead of kk.

still WA

Your numbers can get negative as there is a subtraction operation. Use the additional check

if(ans < 0) ans+=x;

1 Like

u do not need to keep doing %x at every step. The actual result for all test cases remains inside the range of long long so take modulus only at the end. I was doing the same mistake and getting WA somehow.

1 Like

converted ‘ans’ from unsigned to signed long long, and then applied your suggestion got the answer accepted
instead of
if(ans<0) ans += x;
i used
while(ans<0) ans +=x;

thanks

1 Like

You don’t really need a while loop. ans is already calculated modulo x. The only problem is that it can become negative(but still > -x). Your while loop will execute only once, which is fine.