简体   繁体   English

使用jQuery或JavaScript查找2个数字的倍数和余数

[英]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. 奇怪的任务,但是我需要取一个给定的整数,然后将其除以5,除掉剩下的,再除以3,然后显示剩下的。

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. 我可以划分并查看它是否是倍数,但是我不确定如何执行条件语句以将其传递给2个操作,而每次都剩下余数。 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: 在javascript代码中,它是:

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: 您可以在javascript中使用% .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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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