📌  相关文章
📜  检查数组中所有可能对(i,j)的arr [i] / j的总和是否为0

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

给定一个由N个整数组成的数组arr [] ,任务是检查所有对(i,j)(arr [i] / j)的所有可能值的和是否等于0 是否为0 。如果发现是真的,则打印“是” 。否则,打印“否”

例子:

方法:可以根据以下观察结果解决给定问题:

  • 对于范围在[0,N – 1]内的i的每个可能值以及j的每个可能的值,以下表达式为:
    • j = 1: \frac{a_1}{1}  + \frac{a_2}{2} + \frac{a_3}{3} .... +\frac{a_n}{n}
    • j = 2: \frac{a_2}{2} + \frac{a_3}{3} .... +\frac{a_n}{n}
    • j = 3: \frac{a_3}{3} .... +\frac{a_n}{n}     第三行
    • 等等…
  • 因此,以上所有表达式的总和由下式给出:

从上面的观察,如果数组的总和为0 ,则输出Yes 。否则,打印No。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to check if sum of all
// values of (arr[i]/j) for all
// 0 < i <= j < (N - 1) is 0 or not
void check(int arr[], int N)
{
    // Stores the required sum
    int sum = 0;
 
    // Traverse the array
    for (int i = 0; i < N; i++)
        sum += arr[i];
 
    // If the sum is equal to 0
    if (sum == 0)
        cout << "Yes";
 
    // Otherwise
    else
        cout << "No";
}
 
// Driver Code
int main()
{
    int arr[] = { 1, -1, 3, -2, -1 };
    int N = sizeof(arr) / sizeof(arr[0]);
    check(arr, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG{
 
// Function to check if sum of all
// values of (arr[i]/j) for all
// 0 < i <= j < (N - 1) is 0 or not
static void check(int arr[], int N)
{
     
    // Stores the required sum
    int sum = 0;
 
    // Traverse the array
    for(int i = 0; i < N; i++)
        sum += arr[i];
 
    // If the sum is equal to 0
    if (sum == 0)
        System.out.println("Yes");
 
    // Otherwise
    else
        System.out.println("No");
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 1, -1, 3, -2, -1 };
    int N = arr.length;
     
    check(arr, N);
}
}
 
// This code is contributed by Kingash


Python3
# Python3 program for the above approach
 
# Function to check if sum of all
# values of (arr[i]/j) for all
# 0 < i <= j < (N - 1) is 0 or not
def check(arr, N):
     
    # Stores the required sum
    sum = 0
 
    # Traverse the array
    for i in range(N):
        sum += arr[i]
 
    # If the sum is equal to 0
    if (sum == 0):
        print("Yes")
 
    # Otherwise
    else:
        print("No")
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ 1, -1, 3, -2, -1 ]
    N = len(arr)
     
    check(arr, N)
 
# This code is contributed by mohit kumar 29


输出:
Yes

时间复杂度: O(N)
辅助空间: O(1)