可被给定数 K 整除的数组中所有元素的总和
给定一个包含 N 个元素和一个数字 K 的数组。任务是找到所有可以被 K 整除的元素的总和。
例子:
Input : arr[] = {15, 16, 10, 9, 6, 7, 17}
K = 3
Output : 30
Explanation: As 15, 9, 6 are divisible by 3. So, sum of elements divisible by K = 15 + 9 + 6 = 30.
Input : arr[] = {5, 3, 6, 8, 4, 1, 2, 9}
K = 2
Output : 20
思路是遍历数组,一一检查元素。如果一个元素可被 K 整除,则将该元素的值与到目前为止的总和相加,并在到达数组末尾时继续此过程。
下面是上述方法的实现:
C++
// C++ program to find sum of all the elements
// in an array divisible by a given number K
#include
using namespace std;
// Function to find sum of all the elements
// in an array divisible by a given number K
int findSum(int arr[], int n, int k)
{
int sum = 0;
// Traverse the array
for (int i = 0; i < n; i++) {
// If current element is divisible by k
// add it to sum
if (arr[i] % k == 0) {
sum += arr[i];
}
}
// Return calculated sum
return sum;
}
// Driver code
int main()
{
int arr[] = { 15, 16, 10, 9, 6, 7, 17 };
int n = sizeof(arr) / sizeof(arr[0]);
int k = 3;
cout << findSum(arr, n, k);
return 0;
}
Java
// Java program to find sum of all the elements
// in an array divisible by a given number K
import java.io.*;
class GFG {
// Function to find sum of all the elements
// in an array divisible by a given number K
static int findSum(int arr[], int n, int k)
{
int sum = 0;
// Traverse the array
for (int i = 0; i < n; i++) {
// If current element is divisible by k
// add it to sum
if (arr[i] % k == 0) {
sum += arr[i];
}
}
// Return calculated sum
return sum;
}
// Driver code
public static void main (String[] args) {
int arr[] = { 15, 16, 10, 9, 6, 7, 17 };
int n = arr.length;
int k = 3;
System.out.println( findSum(arr, n, k));
}
}
// this code is contributed by anuj_67..
Python3
# Python3 program to find sum of
# all the elements in an array
# divisible by a given number K
# Function to find sum of all
# the elements in an array
# divisible by a given number K
def findSum(arr, n, k) :
sum = 0
# Traverse the array
for i in range(n) :
# If current element is divisible
# by k add it to sum
if arr[i] % k == 0 :
sum += arr[i]
# Return calculated sum
return sum
# Driver code
if __name__ == "__main__" :
arr = [ 15, 16, 10, 9, 6, 7, 17]
n = len(arr)
k = 3
print(findSum(arr, n, k))
# This code is contributed by ANKITRAI1
C#
// C# program to find sum of all the elements
// in an array divisible by a given number K
using System;
public class GFG{
// Function to find sum of all the elements
// in an array divisible by a given number K
static int findSum(int []arr, int n, int k)
{
int sum = 0;
// Traverse the array
for (int i = 0; i < n; i++) {
// If current element is divisible by k
// add it to sum
if (arr[i] % k == 0) {
sum += arr[i];
}
}
// Return calculated sum
return sum;
}
// Driver code
static public void Main (){
int []arr = { 15, 16, 10, 9, 6, 7, 17 };
int n = arr.Length;
int k = 3;
Console.WriteLine( findSum(arr, n, k));
}
}
//This code is contributed by anuj_67..
PHP
Javascript
输出:
30
时间复杂度:O(N),其中 N 是数组中元素的数量。
辅助空间: O(1)