2

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 -

  1. Can we represent T in terms of N ?
  2. If yes, then please help me to convert that.
Will Ness
  • 62,652
  • 8
  • 86
  • 167
devsda
  • 3,746
  • 9
  • 47
  • 82
  • 1
    Loop#2 complexity is O( ln(i) ) *only* for the O(log^3 T) regular numbers themselves, and is O(1) for all O(T) others. – Will Ness Feb 29 '16 at 17:57

1 Answers1

2

The numbers that you're trying to find are called 5-smooth. One of the bounds in the Wikipedia article suggests that there are O(log^3 T) 5-smooth numbers less than T, so given N, we'd need to set T = 2^Omega(N^(1/3)).

If you're trying to enumerate 5-smooth numbers, Dijkstra's algorithm is probably the way to go, returning N numbers in O(N) time.

David Eisenstat
  • 52,844
  • 7
  • 50
  • 103