Sponsored
Sponsored
In this approach, we observe that bulbs that remain on are those that are toggled an odd number of times. Typically, a bulb indexed at i
is toggled once for every divisor it has. Numbers which are perfect squares have an odd number of divisors (since one of its divisors is repeated, for example, the square root). Hence, the number of bulbs that will remain on is determined by the number of perfect squares up to n
. Therefore, the number of bulbs left on is the integer part of the square root of n
.
Time Complexity: O(1) as computing the square root and type casting are constant time operations.
Space Complexity: O(1) since no additional space is used.
1#include <math.h>
2
3int bulbSwitch(int n) {
4 return (int)sqrt(n);
5}
The solution uses the math library to calculate the square root of n
and casts it to an integer, thereby getting the count of perfect squares less than or equal to n
.
This approach involves explicitly counting all perfect squares up to n
by probing through potential perfect squares. Starting from 1, we continue as long as i*i
is less than or equal to n
, incrementing the counter each time. This direct enumeration is straightforward and still only traverses a limited range due to the root domain.
Time Complexity: O(√n), iterates through the square roots from 1 to √n.
Space Complexity: O(1) uses fixed amount of additional space.
1 int count = 0;
for (int i = 1; i * i <= n; i++) {
count++;
}
return count;
}
A straightforward loop that counts potential values of i
satisfying i*i ≤ n
, demonstrating the number of bulbs that stay on.