how to put modulo in the right place for geting ans of large values

,

#include<stdio.h>

#include<math.h>

int main(){
      int t=0;
      long long int res=0,i,n,m,j,k,s1,s2;
       scanf("%d",&t);

       while(t-- > 0){
             scanf("%lld %lld",&n,&m);
             for(i=1;i<=sqrt(n);i++){
              res=(res+(i*i*i*i)*(n/i))%m;
          }
       printf("%lld\n",res);
        k=(--i);
       s1=((i*(1+i)*(1+2*i)*(-1+3*i+3*i*i))/30);
                      
       for(j=sqrt(n);j>=1;j--){
             i=n/j;
             printf("The value of i:%lld\n",i);
             if(i>k){
               s2=(i*(1+i)*(1+2*i)*(-1+3*i+3*i*i))/30;
               s1=s2-s1;
               res=(res+(s1)*j)%m;;
               s1=s2;
               k=i;
             }
         }
         
         printf("%lld\n",res);
         res=0;s1=0;s2=0;
         
}
//getch();
return 0;

}

getting wrong answer.I think i m getting wrong answer for large o/p bcoz of putting modulo in wrong places.plz suggest me how to put modulo in correct places.
link:FLOORI4 Problem - CodeChef

Modular multiplication property:-
Take mod at every step of multiplication i.e

 let mod=10^7+9; 
(a * b * c)%mod=((((a%mod) * (b%mod))%mod) * (c%mod))%mod 

Try to use this property in the line:-

res=(res+(i * i * i * i)*(n/i))%m;

Also Modular Addition property states that:-

 (a+b)%mod=((a%mod)+(b%mod))%mod 

Hope this Helps!
Happy Coding!!!