Given the average of elements in two arrays as ‘a’ and ‘b’ respectively, and their combined average as ‘c’, the task is to find the ratio of the number of elements in two array.
Examples:
Input: a = 2, b = 8, c = 5
Output: 1:1
Input: a = 4, b = 10, c = 6
Output: 2:1
Approach:
- Let the number of elements in two arrays are respectively x and y.
- So sum of all elements in the combined array is
. - Total number of elements in the combined array is
and let
. - So,



So, 
- Here f is our required answer.
Below is the implementation of the above Approach:
C++
#include <bits/stdc++.h>
using namespace std;
void FindRatio( int a, int b, int c)
{
int up = abs (b - c);
int down = abs (c - a);
int g = __gcd(up, down);
up /= g;
down /= g;
cout << up << ":"
<< down << "\n" ;
}
int main()
{
int a = 4, b = 10, c = 6;
FindRatio(a, b, c);
return 0;
}
|
Java
class GFG
{
static int gcd( int a, int b)
{
if (b == 0 )
return a;
return gcd(b, a % b);
}
static void FindRatio( int a, int b, int c)
{
int up = Math.abs(b - c);
int down = Math.abs(c - a);
int g = gcd(up, down);
up /= g;
down /= g;
System.out.println(up + ":" + down);
}
public static void main (String[] args)
{
int a = 4 , b = 10 , c = 6 ;
FindRatio(a, b, c);
}
}
|
Python3
from math import gcd
def FindRatio(a, b, c):
up = abs (b - c)
down = abs (c - a)
g = gcd(up, down)
up / / = g
down / / = g
print (up, ":" , down)
a = 4
b = 10
c = 6
FindRatio(a, b, c)
|
C#
using System;
class GFG
{
static int gcd( int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static void FindRatio( int a, int b, int c)
{
int up = Math.Abs(b - c);
int down = Math.Abs(c - a);
int g = gcd(up, down);
up /= g;
down /= g;
Console.WriteLine(up + ":" + down);
}
public static void Main (String []args)
{
int a = 4, b = 10, c = 6;
FindRatio(a, b, c);
}
}
|
Javascript
<script>
function FindRatio(a, b, c)
{
let up = Math.abs(b - c);
let down = Math.abs(c - a);
let g = gcd(up, down);
up = parseInt(up / g);
down = parseInt(down / g);
document.write(up + ":"
+ down + "<br>" );
}
function gcd(a, b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
let a = 4, b = 10, c = 6;
FindRatio(a, b, c);
</script>
|
Time Complexity: O(log( min(abs(b-c),abs(c-a)) ) )
Auxiliary Space: O(1)