

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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,
#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
- Related Questions & Answers
- Number of pairs from the first N natural numbers whose sum is divisible by K in C++
- Sum of sum of first n natural numbers in C++
- Sum of first n natural numbers in C Program
- Program to find number of pairs from N natural numbers whose sum values are divisible by k in Python
- Program to find sum of first n natural numbers in C++
- Java program to find the sum of n natural numbers
- C Program for the cube sum of first n natural numbers?
- Sum of squares of first n natural numbers in C Program?
- Sum of two numbers modulo M in C++
- C Program for cube sum of first n natural numbers?
- C++ Program for cube sum of first n natural numbers?
- C++ Program for Sum of squares of first n natural numbers?
- Program for cube sum of first n natural numbers in C++
- 8085 program to find the sum of first n natural numbers
- Sum of square-sums of first n natural numbers
Advertisements