Сумма натуральных чисел (до N), которые по модулю K дают R
Опубликовано: 14 Января, 2022
Даны три целых числа N , K и R. Задача состоит в том, чтобы вычислить сумму всех этих чисел от 1 до N, которая дает остаток R при делении на K.
Примеры:
Input: N = 20, K = 4, R = 3
Output: 55
3, 7, 11, 15 and 19 are the only numbers that give 3 as the remainder on division with 4.
3 + 7 + 11 + 15 + 19 = 55
Input: N = 15, K = 13, R = 2
Output: 17
Рекомендуется: сначала попробуйте свой подход в {IDE}, прежде чем переходить к решению.
Подход:
- Инициализируйте sum = 0 и возьмите модуль каждого элемента от 1 до N с помощью K.
- Если остаток равен R , то обновить sum = sum + i, где i - текущее число, которое дало R в качестве остатка при делении на K.
- В конце выведите значение суммы.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;// Function to return the sumlong long int count(int N, int K, int R){ long long int sum = 0; for (int i = 1; i <= N; i++) { // If current number gives R as the // remainder on dividing by K if (i % K == R) // Update the sum sum += i; } // Return the sum return sum;}// Driver codeint main(){ int N = 20, K = 4, R = 3; cout << count(N, K, R); return 0;} |
Java
// Java implementation of the approachclass GfG{// Function to return the sumstatic long count(int N, int K, int R){ long sum = 0; for (int i = 1; i <= N; i++) { // If current number gives R as the // remainder on dividing by K if (i % K == R) // Update the sum sum += i; } // Return the sum return sum;}// Driver codepublic static void main(String[] args){ int N = 20, K = 4, R = 3; System.out.println(count(N, K, R));}}// This code is contributed by// prerna saini. |
Python3
# Python 3 implementation of the approach# Function to return the sumdef count(N, K, R): sum = 0 for i in range(1, N + 1): # If current number gives R as the # remainder on dividing by K if (i % K == R): # Update the sum sum += i # Return the sum return sum# Driver codeif __name__ == "__main__": N = 20 K = 4 R = 3 print(count(N, K, R))# This code is contributed by# Surendra_Gangwar |
C#
// C# implementation of the approachusing System;class GFG{// Function to return the sumstatic long count(int N, int K, int R){ long sum = 0; for (int i = 1; i <= N; i++) { // If current number gives R as the // remainder on dividing by K if (i % K == R) // Update the sum sum += i; } // Return the sum return sum;}// Driver codepublic static void Main(){ int N = 20, K = 4, R = 3; Console.Write(count(N, K, R));}}// This code is contributed by// Akanksha Rai |
PHP
<?php// PHP implementation of the approach// Function to return the sumfunction count1($N, $K, $R){ $sum = 0; for ($i = 1; $i <= $N; $i++) { // If current number gives R as the // remainder on dividing by K if ($i % $K == $R) // Update the sum $sum += $i; } // Return the sum return $sum;}// Driver code$N = 20; $K = 4; $R = 3;echo count1($N, $K, $R);// This code is contributed// by Akanksha Rai?> |
Javascript
<script>// Javascript implementation of the approach // Function to return the sum function count(N , K , R) { var sum = 0; for (i = 1; i <= N; i++) { // If current number gives R as the // remainder on dividing by K if (i % K == R) // Update the sum sum += i; } // Return the sum return sum; } // Driver code var N = 20, K = 4, R = 3; document.write(count(N, K, R));// This code contributed by aashish1995</script> |
Output:
55
Вниманию читателя! Не прекращайте учиться сейчас. Получите все важные математические концепции для соревновательного программирования с курсом Essential Maths for CP по доступной для студентов цене. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .