w3resource

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:

Flowchart: JavaScript Math - calculate the divisor and modulus of two integers

Live Demo:

See the Pen javascript-math-exercise-46 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript function that computes the quotient and remainder of two integers without using the division operator.
  • Write a JavaScript function that uses iterative subtraction to calculate both the divisor and modulus.
  • Write a JavaScript function that implements the division algorithm and returns an object with quotient and remainder.
  • Write a JavaScript function that validates input to ensure proper division before calculating the divisor and modulus.

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.



Follow us on Facebook and Twitter for latest update.