JavaScript: Calculate the divisor and modulus of two integers
JavaScript Math: Exercise-46 with Solution
Calculate Divisor and Modulus
Write a JavaScript function to calculate the divisor and modulus of two integers.
Sample Solution:
JavaScript Code:
// Define a function named div_mod that performs integer division and modulus operation.
function div_mod(a, b)
{
// Check if 'b' is non-positive and throw an error.
if (b <= 0)
throw new Error("b cannot be zero. Undefined.");
// Check if 'a' and 'b' are integers.
if (isInt(a) && !isInt(b))
throw new Error("A or B are not integers.");
// Return an array containing the quotient and remainder of 'a' divided by 'b'.
return [Math.floor(a / b), a % b];
}
// Define a helper function named isInt that checks if a number is an integer.
function isInt(n) {
return n % 1 === 0;
}
// Output the result of performing division and modulus operation on 17 and 4 to the console.
console.log(div_mod(17, 4));
Output:
[4,1]
Flowchart:
Live Demo:
See the Pen javascript-math-exercise-46 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus.
Previous: Write a JavaScript function to subtract elements from one another in an array.
Next: Write a JavaScript function to calculate the extended Euclid Algorithm or extended GCD.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics