
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
Advertisements