Issue with Fuction

solved
Last edited on
I've never heard of this notation, but I understand that it simply checks the number of times a calculation is performed.

1
2
3
4
5
6
7
8
9
10
11
12
13
int january(bool exists)
{
	int sum2=0; int p,j,n;// You need to initialize n or pass it into the function or something.
	if (exists)
		for(p=1; p<=n; p*=2) // O(x) where x = log2(n) or X = log(n)/log(2) rounded up;
			for(j=1; j<=p; j++) // O(p * x) or O(2^x * x) because here we go through the loop x * p times and p = 2^x.
				sum2++;
	else
		for(p=1; p<=n; p*=2) // O(x) where x = log2(n) or X = log(n)/log(2) rounded up (as before)
			for(j=1; j<=n; j++) // O(n * x)
				sum2++;
	return sum2; 
}


Lets take an example where n=30.
1
2
if (exists): p = 1 , 2, 4, 8, 16, sum2 = 16 * 5 = 80
else       : p = 1 , 2, 4, 8, 16, sum2 = 30 * 5 = 150.


If you want to really reduce it,
1
2
if (exists): sum2 = log(n)/log(2) * 2 ^ log(n)/log(2);
else       : sum2 = n * log(n)/log(2);

Just ensure you always round up.

The else part of the statement is larger
Last edited on
It is O(n^2) there is no prob.
Thank you very much! I understood what was wrong.
Topic archived. No new replies allowed.