# Amortized analysis for increment in counter in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

Amortized analysis for a sequence of operations is used to determine the run time, the average time required by the sequence. In cannot be treated as an average-case analysis done on the algorithm as it does not always take the average case scenario. There are cases that occur as a worst-case scenario of analysis. So, amortized analysis can be treated as a worst-case analysis for multiple operations in a sequence. Here, the cost of doing each operations in different and for some its high. This problem is a general view using the binary counter.

Let’s see the working and implementation in c++ programming language so that we will be clear with the concepts.

A k-bit binary counter is implemented using a binary array of length k which is initially valued 0. On this value, the increment operation is performed multiple times. Here is how the binary 8-bit array will behave on the increment operation performed on it.

Initially, 00000000 > 00000001 > 00000010 > 00000011 > 00000100 > 00000101 >.... > 11111111.

This logic is to check for the occurrence of first 0 from the last bit of the number and flip it to 1 and all the bits sequentially following it to 0.

## Example

#include <iostream>
using namespace std;
int main(){
int number[] = {1,0,0,1,0,1,1,1};
int length = 8;
int i = length - 1;
while (number[i] == 1) {
number[i] = 0;
i--;
}
if (i >= 0)
str[i] = 1;
for(int i = 0 ; i<length ; i++)
cout<<number[i]<<" ";
}

## Output

1 0 0 1 0 0 0 0

In this problem, the cost of each operation is constant and does not depend on the number of bits,

Here the asymptotic analysis for the cost of a sequence is O(n).

The total number of flips that are done in n operations is − n + n/2 + n/4 + ….. + n/k2 k in the number of flips.

This is a GP with HP in the denominator.

The sum of flip

Sum = n + n/2 + n/4 + ….. + n/k2 < n/(1-1/2) = 2n

Now, aromatized cost of operation is O(n) / 2n = O(1)

The order is O(1) which is not proportional to n the number of bits in the number.

Updated on 24-Oct-2019 07:54:31