📜  与K取模的自然数之和(最大N)

📅  最后修改于: 2021-05-04 16:13:23             🧑  作者: Mango

给定三个整数NKR。任务是计算从1N的所有这些数字的总和,得出除以K所得的余数为R。

例子:

方法:

  • 初始化sum = 0,并用K将每个元素的模取为1N。
  • 如果余数等于R ,则更新sum = sum + i ,其中i是在除以K时将R作为余数的当前数。
  • 最后打印sum的值。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
  
// Function to return the sum
long 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 code
int main()
{
    int N = 20, K = 4, R = 3;
    cout << count(N, K, R);
  
    return 0;
}


Java
// Java implementation of the approach 
class GfG 
{ 
  
// Function to return the sum 
static 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 code 
public 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 sum
def 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 code
if __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 approach 
using System;
class GFG 
{ 
  
// Function to return the sum 
static 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 code 
public static void Main() 
{ 
    int N = 20, K = 4, R = 3; 
    Console.Write(count(N, K, R)); 
}
} 
  
// This code is contributed by
// Akanksha Rai


PHP


输出:
55