Integer divison using bitwise operators
HTML
<h1>Integer divison using bitwise operators</h1>
<div>
<label for="a">Divisor <i>a</i> =</label>
<input type="text" id="a" value="3" />
</div>
<div>
<label for="m">Dividend <i>n</i> < 2<sup><i>m</i></sup>, where exponent <i>m</i> =</label>
<select id="m">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option selected>7</option>
<option>8</option>
<option>9</option>
<option>10</option>
<option>11</option>
<option>12</option>
<option>13</option>
<option>14</option>
<option>15</option>
<option>16</option>
<option>17</option>
<option>18</option>
<option>19</option>
<option>20</option>
<option>21</option>
<option>22</option>
<option>23</option>
<option>24</option>
<option>25</option>
<option>26</option>
<option>27</option>
<option>28</option>
<option>29</option>
<option>30</option>
<option>31</option>
<option>32</option>
</select>
</div>
<div>
<input type="button" id="generate" value="Generate formula" />
</div>
<div>Formula: <span id="formula">---</span>
</div>
CSS
* {
margin: 0;
padding: 0;
font:"Times" 1em;
}
h1, div {
margin: 10px;
}
input[type="button"] {
padding: 5px;
}
input[type="text"], select {
width: 50px;
}
JavaScript
var $a = $("#a"),
$m = $("#m"),
$generate = $("#generate"),
$formula = $("#formula");
$generate.click(function () {
var a = +$a.val(),
m = +$m.val(),
m2 = 0,
k = 0;
if (isNaN(a) || a !== Math.floor(a) || a < 2 || a > Math.pow(2, 31) - 1) {
alert("Divisor \"a\" must be an integer between 2 and 2^32-1");
return;
}
m2 = Math.pow(2, m);
k = Math.ceil(m2 / a);
$formula.html("<i>n</i> / " + a + " = (" + k + " * <i>n</i>) >> " + m + "; for all <i>n</i> < " + m2);
});
$generate.click();