Skip to content

Commit

Permalink
Add solution to day 27
Browse files Browse the repository at this point in the history
  • Loading branch information
AhmedGamal2212 committed Apr 27, 2023
1 parent db7dda3 commit c5ec916
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions 04- April/27- Bulb Switcher/27- Bulb Switcher (Ahmed Gamal).js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// Autor: Ahmed Gamal

// the idea for this solution is so simple, let's look at the following observations:
// 1- each bulb will be on after the number of its factors is odd
// 2- each number has even number of factors except the perfect squares (because each factor has a pair in the other side of the number, except the perfect squares)
// 3- so the number of bulbs that will be on is the number of perfect squares less than n

// since the perfect squares are growing so fast, we will loop until the square of the number is less than or equal n (at most sqrt(n))

// or we can use the following formula to calculate the number of perfect squares less than n:
// Math.floor(Math.sqrt(n)), why?
// because the perfect squares are the squares of the numbers from 1 to Math.floor(Math.sqrt(n)), so every integer from 1 to Math.floor(Math.sqrt(n)) will have a perfect square less than or equal n, so the number of perfect squares less than n is Math.floor(Math.sqrt(n))

/**
* @param {number} n
* @return {number}
*/
var bulbSwitch = function(n) {
return Math.floor(Math.sqrt(n));
};

0 comments on commit c5ec916

Please sign in to comment.