Modulo of 24 digit long integer? - javascript

I need to calculate the modulo of a 24 digit long integer (IBAN checksum) but JS calculates wrong.
e.g.:
700901001234567890131400 % 97 = 90
but in JS (V8) it's 38.
How can I calculate the modulo in JS

I think the document you're linking to already says what you should do:
If the application software in use does not provide the ability to handle integers of this size, the modulo operation can be performed in a piece-wise manner.
Piece-wise calculation D mod 97 can be done in many ways. One such way is as follows:
Starting from the leftmost digit of D, construct a number using the first 9 digits and call it N.[Note 3]
Calculate N mod 97.
Construct a new 9-digit N by concatenating above result (step 2) with the next 7 digits of D. If there are fewer than 7 digits remaining in D but at least one, then construct a new N, which will have less than 9 digits, from the above result (step 2) followed by the remaining digits of D
Repeat steps 2–3 until all the digits of D have been processed
The result of the final calculation in step 2 will be D mod 97 = N mod 97.

It might be harder than one can think.
It's quite tricky to ensure javascript handle number as integer (it often store them as float, but not always).
Others already made libraries to handle IBAN check in JS.
Take a look at https://github.com/arhs/iban.js for instance.

The largest number that can be represented in javascript is 2^53 - 1. They are 64-bit floating point values. So the largest number is 9007199254740991.
A number greater than 9007199254740991 can not be caclcuted in normal way. So, to find the modulo of such large number you have to break it into pieces.
eg. 700901001234567890131400 can be broken into 700901001234567 and 890131400.
First find the modulo of 700901001234567.
700901001234567 % 97 = 13
Now join 13 infront of second number 13890131400 and find the modulo of this number
13890131400 % 97 = 90

I came across this problem recently and this looks like what is solvable with Horner's method [https://en.wikipedia.org/wiki/Horner%27s_method]
/**
* str is numeric.
* MOD=97 is our use case
* #return: an integer 0<=x<=97
**/
int getMod(String str, int MOD) {
int remainder = 0;
for(Character c : str.toCharArray()) {
int value = Character.getNumericValue(c);
remainder = 10*remainder + value;
remainder %= MOD;
}
return remainder;
}
Unless I don't fully understand the problem, the code above should work.

Related

Mathematical formula for Math.clz32

I was trying to implement the Javascript-method Math.clz32 in Python. The method I've been able to come up with is:
def clz32(x):
x = x % 2 ** 32
if x == 0: return 32
return 34 - len(bin(x))
This method works, but I've been wondering whether there is a pure mathematical formula for this.
You can use the bit_length method, which returns the number of bits required to represent the integer. Since we are only interested in the leading zero bits, we will subtract this number from 32. Note that this does not account for negative numbers, so clz32(-1) will return 0.
def clz32(x):
if x < 0:
return 0
return 32 - x.bit_length()

Is there a condition where the Math.ceil function in Javascript doesn't remove decimals from the output?

Is there a reason why some Javascript programmers use the following syntax to remove decimals?
Math.ceil(averageCost / 10) * 10;
Why wouldn't we just use Math.ceil? Doesn't it effectively do the same thing as the above? Is there a condition where Math.ceil doesn't work?
Initially I thought maybe this would eliminate string cases and return a zero, but in the following code, the results are NaN -
var name = "Gary";
console.log(Math.ceil(name / 10)); // NaN
console.log(Math.ceil(name)); // NaN
So I'm at a loss for why I'd see a division by 10 with a subsequent multiplication of 10.
The construct:
Math.ceil(averageCost / 10) * 10;
Does a form of rounding. It has the net effect of rounding up to the nearest whole number multiple of 10. So:
11 => 20
20 => 20
21 => 30
11.99 => 20
Math.ceil(averageCost / 10) divides by 10 and rounds up to the nearest whole number (removing all decimal portions and all ones) and then the * 10 brings it back to the same numeric range it was originally in, but without the parts removed by the rounding.
Here's an example showing a number of results:
const nums = [10,11,15,18,19,20,21,10.1,11.99,20.19];
for (let num of nums) {
let result = Math.ceil(num/10) * 10;
console.log("Input: ", num, ", Output: ", result);
}
Why wouldn't we just use Math.ceil? Doesn't it effectively do the same thing as the above? Is there a condition where Math.ceil doesn't work?
This combination rounds up to the nearest whole number multiple of 10 whereas Math.ceil() only rounds up to the nearest whole number. So, the two cases you ask about have different uses. Use the one that accomplishes what you want to accomplish. For a number where the integer portion is already a power of ten such as 10.3, the two would have the same output, but for any other number such as 11.3, the two would not have the same output.
Math.ceil(11.3) === 11
(Math.ceil(11.3 / 10) * 10) === 20
Is there a condition where the Math.ceil() function in Javascript doesn't remove decimals from the output?
No. There is not. It's whole function is to round up to the nearest whole number (thus removing any decimal fraction from the number).
So I'm at a loss for why I'd see a division by 10 with a subsequent multiplication of 10.
To round up to the nearest whole number multiple of 10.

How to avoid "Infinity" and console.log a large number in Javascript?

I am trying to find the first number in the Fibonacci sequence to contain over 1000 digits.
Given a number n (e.g. 4), I found a way to find what place the first number with n-digits has in the Fibonacci sequence as well as a way to find the number given its place in the sequence.
Say, for example, you need to know the first number with 4 digits in the Fibonacci sequence as well as its place in the sequence. My code would work like this:
var phi = (1+Math.sqrt(5))/2;
var nDigits = 4;
var fEntry = Math.ceil(2 + Math.log(Math.pow(10, nDigits-
1))/Math.log(phi));
var fNumber = 2 * Math.pow(phi, fEntry);
console.log(fEntry);
console.log(fNumber);
In the console you would see fEntry (that is, the place the number has in the Fibonacci sequence) and fNumber (the number you're looking for). If you want to find the first number with 4 digits and its place in the sequence, for example, you'll get number 1597 at place 17, which is correct.
So far so good.
Problems arise when I want to find big numbers. I need to find the first number with 1000 digits in the Fibonacci sequence, but when I write nDigits = 1000 and run the code, the console displays "Infinity" for fEntry and for fNumber. I guess the reason is that my code involves calculations with numbers higher than what Javascript can deal with.
How can I find that number and avoid Infinity?
How can I find that number and avoid Infinity?
You can't, with the number type. Although it can hold massive values, it loses integer accuracy after Number.MAX_SAFE_INTEGER (9,007,199,254,740,991):
const a = Number.MAX_SAFE_INTEGER;
console.log(a); // 9007199254740991
console.log(a + 1); // 9007199254740992, so far so good
console.log(a + 2); // 9007199254740992, oh dear...
You can use the new BigInt on platforms that support it. Alternately, any of several "big int" libraries that store the numbers as strings of digits (literally).

Extract bits from start to end in javascript

In Java script I want to extract bits 13 to 16 from integer number.
Example: If I extract bits 13 to 16 from number 16640 then output will be 2
I have searched on google and found few links but they are in C language.
Assuming your bit count starts at 0:
var extracted, orig;
orig = parseInt("16640", 10); // best practice on using parseInt: specify number base to avoid spurious octal interpretation on leading zeroes (thx Ken Fyrstenberg)
extracted = ((orig & ((1 << 16) - 1) & ~(((1 << 13) - 1))) >>> 13);
Explanation:
mask the lower 16 bits of the original number
mask the complement of the lower 13 bits of the result (ie. bits 13-31)
you currently have bits 13-16 of the orignal number in their original position. shift this bit pattern 13 bits to the right.
Note that this method only works reliably for numbers less than 2^31. The docs (MDN) are here
Javascript's bitwise operations work essentially the same way as they do in C:
var bits13to16 = (number >> 13) & 15;
This shifts the number 13 bits to the right (eliminating bits 0-12) and masks all but the last 4 remaining bits (which used to be bits 13-16). 15 = 2^4 - 1.
All suggestions are working but the simplest I think is given by #dandavis.
parseInt( 16640 .toString(2).slice(-16, -13), 2 );

Next odd number in javascript

To find the next odd number for an input the following code is being used:
a=5.4; // Input
b=Math.ceil(a); // Required to turn input to whole number
b=b+(((b % 2)-1)*-1); // Gives 7
The ceil rounding function is required.
Is this safe and is there a more compact way to do this?
EDIT: When the input is already an odd whole number then nothing happens. For example 5.0 will return 5
How about just
b += b % 2 ^ 1;
The remainder after dividing by 2 will always be 0 or 1, so the ^ operator (exclusive-OR) flips it to the opposite.
(Also, (b & 1) ^ 1 would work too. Oh, I guess b = b ^ 1 would work for positive integers, but it'd be problematic for big integers.)
At the question author's request:
The most compact way to achieve it is
b = Math.ceil(a) | 1;
First use ceil() to obtain the smallest integer not smaller than a, then obtain the smallest odd integer not smaller than ceil(a) by doing a bitwise or with 1 to ensure the last bit is set without changing anything else.
To obtain the smallest odd integer strictly larger than a, use
b = Math.floor(a+1) | 1;
Caveats:
Bit-operators operate on signed 32-bit integers in Javascript, so the value of a must be smaller than or equal to 2^31-1, resp. strictly smaller for the second. Also, a must be larger than -2^31-1.
If the representation of signed integers is not two's complement, but ones' complement or sign-and-magnitude (I don't know whether Javascript allows that, Java doesn't, but it's a possibility in C), the value of a must be larger than -1 -- the result of Math.ceil(a) resp. Math.floor(a+1) must be nonnegative.
Not really shorter, but this is more legible:
a=5.4;
b=Math.ceil(a);
b = b % 2 ? b : b + 1;
Try this:
a = 5.4
b = Math.ceil(a)
b = b%2 == 0 ? b+1 : b
y = Math.ceil((x - 1)/2)*2 + 1
Execute fn on http://www.intmath.com/functions-and-graphs/graphs-using-jsxgraph.php
Without Math.ceil() it can be done so:
b = a + a % 2 | 0 + 1;
NB. I consider next odd number of 5.0 as 7.

Categories

Resources