Sum of the natural numbers (up to N) whose modulo with K yield R in C++


In this problem, we are given three numbers N, K and R. Our task is to create a program to find the Sum of the natural numbers (up to N) whose modulo with K yield R.

We will add all the numbers less than N that satisfy the following condition, i%K == R.

Let’s take an example to understand the problem,

Input 

N = 14, K = 4, R = 1

Output 

28

Explanation − All the numbers less than N, that given 1 as remainder when divided by 4 are 1, 5, 9, 13.

To solve this problem, we will loop from R to N, and increment the value by K. So, that we will get eveny number that satisfies the given condition. And add them to the sum.

Here, we could have used to normal loop i.e. with 1 as an interval. But we have used this before it will consume less time.

Example

Program to illustrate the solution,

 Live Demo

#include <iostream>
using namespace std;
int CalcSumofRem(int N, int K, int R){
   int sum = 0;
   for (int i = R; i <= N; i+= K) {
      if (i % K == R)
         sum += i;
   }
   return sum;
}
int main(){
   int N = 14, K = 4, R = 1;
   cout<<"Sum of natural numbers (up to "<<N<<") whose modulo with "<<K<<" yields "<<R<<" is "<<CalcSumofRem(N, K, R);
   return 0;
}

Output

Sum of natural numbers (up to 14) whose modulo with 4 yields 1 is 28

Updated on: 06-Aug-2020

190 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements