Open In App

Fast average of two numbers without division

Improve
Improve
Like Article
Like
Save
Share
Report

Given two numbers, find floor of their average without using division.

Input : x = 10, y = 12
Output : 11

Input : x = 10, y = 7
Output : 8
We take floor of sum.

The idea is to use right shift operator, instead of doing (x + y)/2, we do (x + y) >> 1  

C++
// C++ program to find average without using
// division.
#include <bits/stdc++.h>
using namespace std;

int floorAvg(int x, int y) { 
     return (x + y) >> 1; }

int main() {
  int x = 10, y = 20;
  cout << "Average = " << floorAvg(x, y) <<endl;
  return 0;
}

// This code is contributed by famously.
C
// C program to find average without using
// division.
#include <stdio.h>

int floorAvg(int x, int y) { 
     return (x + y) >> 1; }

int main() {
  int x = 10, y = 20;
  printf("\n\nAverage = %d\n\n", floorAvg(x, y));
  return 0;
}
Java
// Java program to find average 
// without using division
class GFG 
{
    static int floorAvg(int x, int y) {
    return (x + y) >> 1; }
    
    // Driver code
    public static void main (String[] args)
    {
        int x = 10, y = 20;
        System.out.print(floorAvg(x, y));
    }
}

// This code is contributed by Anant Agarwal.
C#
// C# program to find average 
// without using division
using System;

class GFG 
{
    static int floorAvg(int x, int y) 
    {
      return (x + y) >> 1; 
    }
    
    // Driver code
    public static void Main (String[] args)
    {
        int x = 10, y = 20;
        Console.Write("Average = ");
        Console.Write(floorAvg(x, y));
    }
}

// This code is contributed by parashar...
Javascript
<script>

// Javascript program to find 
// average without using 
// division. 
function floorAvg(x, y) 
{
    return (x + y) >> 1; 
} 

// Driver code
var x = 10, y = 20; 

document.write("Average = " + floorAvg(x, y)); 

// This code is contributed by noob2000

</script>
PHP
<?php
// PHP program to find average
// without using division.

// function returns 
// the average
function floorAvg($x, $y)
{ 
    return ($x + $y) >> 1; 
    
}

    // Driver Code
    $x = 10;
    $y = 20;
    echo "Average = ", floorAvg($x, $y);

// This Code is contributed by Ajit
?>
Python3
# Python3 program to find average
# without using division.
def floorAvg(x, y):
    return (x + y) >> 1

# Driver code
x = 10
y = 20

print("Average ", floorAvg(x, y))

# This code is contributed by sunny singh

Output
Average = 15

Time Complexity : O(1)

Auxiliary Space: O(1)

Applications : 
We need floor of average of two numbers in many standard algorithms like Merge Sort, Binary Search, etc. Since we use bitwise operator instead of division, the above way of finding average is faster.
 



Last Updated : 14 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads