Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Finding special type of numbers - JavaScript
In the decimal number system, all the real numbers can be divided into two groups:
- Rational Numbers
- Irrational Numbers
For the scope of this problem we will only discuss the rational numbers. All those numbers which can be written in the p/q form (where q ? 0) are called rational numbers, like 14, 4.6, 3.33333... and many more.
The rational numbers can further be divided into two groups:
- Terminating decimal numbers
- Repeating decimal numbers
This categorization is made on the basis of the result obtained upon dividing p by q.
Rule for Terminating Decimals
The rule for this categorization is that:
- We will obtain a terminating decimal number if and only if the prime factors of q are only 2 and 5
- We will obtain a repeating decimal number if the prime factors of q include any other number than 2 or 5
So, we need to write a JavaScript function that takes in a number representing the value q. Our function should return true if for that value we can obtain a terminating decimal number, false otherwise.
Algorithm
The approach is to keep dividing the number by 2 and 5 as long as possible. If we can reduce the number to 1, it means all prime factors were only 2 and 5, so it's a terminating decimal.
Example
const num = 1250;
const isTerminating = num => {
while(num !== 1) {
if(num % 2 === 0) {
num /= 2;
} else if(num % 5 === 0) {
num /= 5;
} else {
return false;
}
}
return true;
};
console.log(isTerminating(num));
true
How It Works
Let's trace through the example with num = 1250:
- 1250 ÷ 2 = 625
- 625 ÷ 5 = 125
- 125 ÷ 5 = 25
- 25 ÷ 5 = 5
- 5 ÷ 5 = 1
Since we reached 1, all prime factors were only 2 and 5, so 1250 produces a terminating decimal.
Testing with Different Numbers
const isTerminating = num => {
while(num !== 1) {
if(num % 2 === 0) {
num /= 2;
} else if(num % 5 === 0) {
num /= 5;
} else {
return false;
}
}
return true;
};
// Test cases
console.log("Testing 8:", isTerminating(8)); // true (2^3)
console.log("Testing 10:", isTerminating(10)); // true (2 × 5)
console.log("Testing 6:", isTerminating(6)); // false (2 × 3)
console.log("Testing 15:", isTerminating(15)); // false (3 × 5)
Testing 8: true Testing 10: true Testing 6: false Testing 15: false
Conclusion
A rational number produces a terminating decimal if its denominator has only 2 and 5 as prime factors. Our algorithm efficiently checks this by repeatedly dividing by 2 and 5 until either we reach 1 (terminating) or find another prime factor (non-terminating).
