简体   繁体   中英

Using jQuery or JavaScript to find multiples and remainder of 2 numbers

Odd task, but I need to take a given integer, and first divide it by 5, whatever is left, divide by 3, and then show whatever remains.

For instance:

var fives = 19 / 5 = 3 remainder 4
var threes = 4 / 3 = 1 remainder 1
var ones = 1


var fives // 3
var threes // 1
var ones // 1

I can divide and see if it's a multiple, but I'm not sure how to do the conditional statement to pass it through the 2 operations and leave the remainders each time. The integers will always be positive numbers, no decimals.

To get the remainder of a division you have to devide, floor it and multiply it again. That result you have to substrate from your starting number.

Example:

Remainder of 19 / 5: 19 - floor(19 / 5)*5 = 19 - 15 = 4

in javascript code it's:

var remainderOf = (a,b)=>a-Math.floor(a / b)*b;
// calling it:
var result = remainderOf(19, 5); // 4

But the operation sequence: divide, floor, multiply substrate... is known as modulo operation. And you can use it in javascript with the % .sign:

var remainderOf = (a,b)=>a%b;

In your case it should be:

var startingNo = 19;
var remainderOfDevisionBy5 = startingNo % 5;
var remainderOfDevisionBy3 = remainderOfDevisionBy5 % 3;
alert(remainderOfDevisionBy3);

How about this:

var number = 19;

var fives = Math.floor(number / 5);
var threes = Math.floor(number % 5 / 3);
var ones = number % 5 % 3;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM