Fast average of two numbers without division in C++


In this problem, we are given two numbers A and B. Our task is to create a program to calculate the Fast average of two numbers without division. 

Let’s take an example to understand the problem,

Input: A = 34       B = 54

Output: 44

Solution Approach: 

Normally, the average is calculated by adding two numbers and then divide it by 2. This requires division but we need to find the average without using division. This can be done using right shift operator >> and shift the binary expansion instead of using division operator.

Program to illustrate the working of our solution,

Example

Live Demo

#include <iostream>
#include <stdio.h>
using namespace std;

int calcAvgWODiv(int A, int B) {
   int average = (A + B) >> 1;
   return average;
}

int main() {
   int A = 123 , B = 653;
   cout<<"The average of the number is "<<calcAvgWODiv(A, B);
   return 0;
}

Output −

The average of the number is 388

Updated on: 22-Jan-2021

278 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements