Norway


Find the of number of series after the element of from element.

Examples:

Input : 3 7 9   18
Explanation:  3 + 7/3 + 9/7 + /9 + 
12/ + 18/12 = 9 (taking only integer 
part)   
Output : 9

Input : 1 12 24 30 60
Output : 18

Approach: We take elements in an array and divide the element from previous element. We do this process for all the elements of an array except very first element. Add the result after division and very first element.

Note: If any element is zero in an array then it fails to do the task and return minus one.

C++

// C++  program for divide and
// sum the number of series
#include <bits/stdc++.h>
using namespace std;

int divideAndSum(int arr[], int n)
{
    int sum = 0;
    for (int i = 0; i < n; i++) {
        
        // checking whether element 
        // is zero or not
        if (arr[i] == 0) 
            return -1;
        
        if (i == 0)
            sum += arr[i];
        else

            // divide element from
            // previous element
            sum += arr[i] / arr[i - 1];
    }
    
    return sum;
}

// Driver code
int main()
{
    int arr[] = { 3, 7, 9, 10, 12, 18 };
    int n = sizeof(arr)/sizeof(arr[0]);
    cout << divideAndSum(arr, n);
    return 0;
}

Output:

9

- avatar - Array sum after dividing numbers from previous

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.




Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.




Source link

LEAVE A REPLY

Please enter your comment!
Please enter your name here