1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|
#include <iostream>
#include <iomanip>
int cnt = 0 ;
int f( int a[], int n )
{
int x=0, i, j;
for(i=1; i<n; i=i*2) // this loop executes for i == 1, 2, 4, 8, 16, 32 ... n-1
{
for(j=0; j<i; j++) // each time, this loop executes i times
// the total number of times this loop executes is therefore:
// i times each time, for i == 1, 2, 4, 8, 16, 32, .. n-1
// ie. 1 + 2 + 4 + 8 + 16 + 32 + ... + (n-1)
// ie. 2 ^ log(n-1) (note: this step is easy if we recall binary representation of integers)
// ie. n-1
// complexity of the algorithm is O(n-1)
// or in asymptotic notation: O(n)
{
x += a[j];
++cnt ;
}
++n ;
}
return x;
}
template < int N > struct test : test<N/2>
{
test()
{
cnt = 0 ;
int a[N] {} ;
f( a, N ) ;
std::cout << std::setw(10) << N << std::setw(10) << cnt
<< std::setw(10) << (2*N)-1 << '\n' ;
}
};
template <> struct test<1> {};
int main()
{
std::cout << std::setw(10) << " N" << std::setw(10) << " cnt"
<< std::setw(10) << " (2*N)-1" << "\n----------------------------------\n" ;
test<1024*1024>() ;
}
|