给定一个由正整数和整数N组成的数组arr[] ,任务是找到所有数组元素的总和,这些元素是N 的倍数
例子:
Input: arr[] = {1, 2, 3, 5, 6}, N = 3
Output: 9
Explanation: From the given array, 3 and 6 are multiples of 3. Therefore, sum = 3 + 6 = 9.
Input: arr[] = {1, 2, 3, 5, 7, 11, 13}, N = 5
Output: 5
方法:这个想法是遍历数组,对于每个数组元素,检查它是否是N的倍数并添加这些元素。请按照以下步骤解决问题:
- 初始化一个变量,比如sum ,以存储所需的总和。
- 遍历给定的数组并对每个数组元素执行以下操作。
- 检查数组元素是否是N的倍数。
- 如果元素是N的倍数,则将该元素添加到sum 。
- 最后,打印sum的值。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to find the sum of array
// elements which are multiples of N
void mulsum(int arr[], int n, int N)
{
// Stores the sum
int sum = 0;
// Traverse the given array
for (int i = 0; i < n; i++) {
// If current element
// is a multiple of N
if (arr[i] % N == 0) {
sum = sum + arr[i];
}
}
// Print total sum
cout << sum;
}
// Driver Code
int main()
{
// Given arr[]
int arr[] = { 1, 2, 3, 5, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
int N = 3;
mulsum(arr, n, N);
return 0;
}
Java
// Java program for the above approach
import java.io.*;
import java.util.*;
class GFG{
// Function to find the sum of array
// elements which are multiples of N
static void mulsum(int arr[], int n, int N)
{
// Stores the sum
int sum = 0;
// Traverse the given array
for (int i = 0; i < n; i++)
{
// If current element
// is a multiple of N
if (arr[i] % N == 0)
{
sum = sum + arr[i];
}
}
// Print total sum
System.out.println(sum);
}
// Driver Code
public static void main(String[] args)
{
// Given arr[]
int arr[] = { 1, 2, 3, 5, 6 };
int n = arr.length;
int N = 3;
mulsum(arr, n, N);
}
}
// This code is contributed by jana_sayantan.
Python
# Python3 program for the above approach
# Function to find the sum of array
# elements which are multiples of N
def mulsum(arr, n, N):
# Stores the sum
sums = 0
# Traverse the array
for i in range(0, n):
if arr[i] % N == 0:
sums = sums + arr[i]
# Print total sum
print(sums)
# Driver Code
if __name__ == "__main__":
# Given arr[]
arr = [ 1, 2, 3, 5, 6 ]
n = len(arr)
N = 3
# Function call
mulsum(arr, n, N)
C#
// C# program for the above approach
using System;
public class GFG
{
// Function to find the sum of array
// elements which are multiples of N
static void mulsum(int[] arr, int n, int N)
{
// Stores the sum
int sum = 0;
// Traverse the given array
for (int i = 0; i < n; i++)
{
// If current element
// is a multiple of N
if (arr[i] % N == 0)
{
sum = sum + arr[i];
}
}
// Print total sum
Console.Write(sum);
}
// Driver Code
static public void Main ()
{
// Given arr[]
int[] arr = { 1, 2, 3, 5, 6 };
int n = arr.Length;
int N = 3;
mulsum(arr, n, N);
}
}
// This code is contributed by Dharanendra L V.
Javascript
输出:
9
时间复杂度: O(N)
辅助空间: O(1)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live