jeudi 24 mai 2018

How can I improve performance for my code?

 /*This Code finds the sum of all multiples of  3 or 5 for a given range of numbers. For example for n=10, no. of the multiple of 3 or 5 below 10 are 3,5,6,9 & their sum is 23.*/
    int main(){
      int t;   //Number of test cases
        cin >> t;
        for(int a0 = 0; a0 < t; a0++){
            int sum=0;
            int n;     //number till which we want to calculate sum.
            cin >> n;  //eg. 10 or 100 
            for( int i=0;i<n;i++){
                     if(i%3==0||i%5==0){
                   sum+=i;  //3,5,6 & 9 are added here
               }
             }
            cout<<sum<<endl; //SUM OF ALL MULTIPLES OF 3 OR 5 RETURNED HERE.
     }
        return 0;
    }

THERE IS A TIMEOUT FOR Large values of n. Can anyone tell me how to improve this code for best result and test cases for higher values of n?

Aucun commentaire:

Enregistrer un commentaire