Related Articles

Related Articles

Fast average of two numbers without division
  • Difficulty Level : Medium
  • Last Updated : 09 May, 2018

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

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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.

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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...

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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
?>

chevron_right


Output:

Average = 15

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.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :