Problem - What is the complexity to find first N numbers that are only divisible by 2, 3, 5 ?
My effort
Code -
void printFirstNNumbers(int N) {
int numbersFound = 0;
// loop#1
for(int cnt = 0; ; cnt++) {
int currentNumber = cnt;
// loop#2
while(currentNumber != 1) {
if(currenNumber%2 == 0) currentNumber /= 2;
else if(currentNumber%3 == 0) currentNumber /= 3;
else if(currentNumber%5 == 0) currentNumber /= 5;
else break;
}
if(currentNumber == 1) {
cout << currentNumber;
numbersFound++;
if(numbersFound == N) return;
}
}
}
Complexity calculation -
Loop#2 complexity - O( ln(i) ), this comes when every time number is divisible by 2, and finally it reaches to 1.
Loop#1 complexity - O(T), where T is the numbers of times it iterates to get first N numbers.
So the complexity is summation of ln(i), where i = 2 to T.
C = summation of ln(i), where i = 2 to T.
2^C = 2*3*....T = factorial(T)
C = ln( factorial(T) )
where factorial(N) = sqrt(2*pie*N)* (N/e)^N
means, factorial(N) directly proportional to (N)^(3N/2)
By above equation,
C = ln ( (T)^(3T/2) ) = (3T/2) ln(T)
C = O(T ln(T) ).
Questions -
- Can we represent T in terms of N ?
- If yes, then please help me to convert that.