
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding Number of Open Water Taps After N Chances Using JavaScript
Problem
Suppose a school organises this game on their Annual Day celebration −
There are ”n” water taps and “n” students are chosen at random. The instructor asks the first student to go to every tap and open it. Then he has the second student go to every second tap and close it. The third goes to every third tap and, if it is closed, he opens it, and if it is open, he closes it. The fourth student does this to every fourth tap, and so on. After the process is completed with the "n"th student, how many taps are open?
We are required to write a JavaScript function that takes in the number n and returns the number of open water taps.
Example
Following is the code −
const num = 15; const openTaps = (num = 1) => { const arr = []; let index = 1; while(index ** 2 <= num){ arr.push(index++ ** 2); }; return arr.length; }; console.log(openTaps(num));
Output
7
Advertisements