
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
Reduce Array to Single Element with Given Operation in C++
Given an integer variable Number as input. Let us consider an array containing elements in the range 1 to Number in sorted order. If we perform an operation on an array such that at each step the elements at odd positions are removed. Then the goal is to perform this operation N number of times till only a single element is left. Print that element at the end.
Note-: The positioning of elements is such that the array at index 0 is at 1st position and so on.
Test Cases for Number of elements in array
Input Number=1, output = 1
Input Number=2, output = 2
Input Number=3, output = 2
Input Number=4, output = 4
Input Number=5, output = 4
Input Number=6, output = 4
Input Number=7, output = 4
......
Input Number=12, output = 8
Input Number=20, output = 16
Based on the above observation, for the range of numbers between 2i to 2i+1-1 output will be 2i.
Examples
Input −Number=7
Output − The single element after reduction operation is : 4
Explanation − First element is at position 1 and so on.
The array will be [ 1 2 3 4 5 6 7 ]
After 1st Operation: [ 2 4 6 ]
After 2nd Operation: [ 4 ]
Input − Number=18
Output − The single element after reduction operation is : 4
Explanation − First element is at position 1 and so on.
The array will be [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 ]
After 1st Operation: [ 2 4 6 8 10 12 14 16 18]
After 2nd Operation: [ 2 8 12 16 ]
After 3rd Operation: [ 8 16 ]
After 4th operation [ 16 ]
Approach used in the below program is as follows
In this approach we will use a while loop to calculate the end result based on the above formula. Take initial value as 2 and traverse till 2*result <= input number and double the value at each iteration.
Take the input variable Number
Function getsingleElement(long num) takes the input number and prints the result based on the above formula.
Take a variable result.
Initialize result with 2.
Traverse using while loop till result*2<=num.
Double result inside will.
As soon as the while loop ends we will get the desired value.
Return result.
Print the result inside main.
Example
#include<bits/stdc++.h> using namespace std; long getsingleElement(long num){ long result; result=2; while(result*2 <= num){ result=result*2; } return result; } int main(){ int Number = 20; cout<<"The single element after reduction operation is : "<<getsingleElement(Number) ; return 0; }
Output
If we run the above code it will generate the following Output
The single element after reduction operation is : 16