- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 Articles
- Number of pairs from the first N natural numbers whose sum is divisible by K in C++
- Program to find number of pairs from N natural numbers whose sum values are divisible by k in Python
- Sum of sum of first n natural numbers in C++
- Sum of two numbers modulo M in C++
- Sum of first n natural numbers in C Program
- Program to find sum of first n natural numbers in C++
- Sum of squares of first n natural numbers in C Program?
- C Program for the cube sum of first n natural numbers?
- Java program to find the sum of n natural numbers
- Find the Minimum Number of Fibonacci Numbers Whose Sum Is K in C++
- Count numbers < = N whose difference with the count of primes upto them is > = K in C++
- C++ Program to calculate the sum of all odd numbers up to N
- Program for cube sum of first n natural numbers in C++
- C++ Program for cube sum of first n natural numbers?
- C Program for cube sum of first n natural numbers?

Advertisements