Multiply strings - javascript

Problem Set- Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.
My algorithm seems to work fine for all but one test case of palindrome from 1-9
UPDATE
Javascript has a parse method but I don't want to use that as the problem is from leetcode or a matter of fact from any such site and the problem sets says that explicitly.
//**Input:**
var n1 = "123456789"
var n2 = "987654321"
var multiply = function(str1, str2) {
var sum = 0, k = 1;
for( var i = str1.length - 1; i>=0; i--){
var val1 = parseInt(str1[i], 10) * k;
k *= 10;
var d = 1;
for(var j = str2.length - 1; j >=0; j--){
var val2 = parseInt(str2[j], 10) * d;
d *= 10;
sum += val1 * val2;
}
}
return sum.toString();
};
console.log(multiply(n1,n2))
I cannot understand what's going wrong. Other palindromes work fine though.

The purpose of such an exercise is probably that you implement your own multiplication algorithm for big numbers. When an integer (the product in this case) needs more than 15-16 digits, JavaScript number type cannot store that with enough precision, and so the outcome will be wrong if you just use the multiplication operator on the inputs.
Even if you sum up smaller products in a number variable, that sum will eventually cross the limit of Number.MAX_SAFE_INTEGER. You need to store the result of smaller calculations in another data structure, like an array or a string.
Here is a simple implementation of the long multiplication algorithm:
function multiply(a, b) {
const product = Array(a.length+b.length).fill(0);
for (let i = a.length; i--; null) {
let carry = 0;
for (let j = b.length; j--; null) {
product[1+i+j] += carry + a[i]*b[j];
carry = Math.floor(product[1+i+j] / 10);
product[1+i+j] = product[1+i+j] % 10;
}
product[i] += carry;
}
return product.join("").replace(/^0*(\d)/, "$1");
}
console.log(multiply("123456789", "987654321"));
Since ECMAScript 2020, JavaScript has the bigint data type, with which you can do such multiplications out of the box (note the n suffix):
console.log((123456789n * 987654321n).toString());
NB: In a browser you don't need to call toString() explicitly, but the above Stack Snippet console implementation is limited, so it needs it.

With Chrome you have access to BigInt arithmetic with arbitrarily (usual disclaimers apply) large integers. Run the example to see that it does make a difference.
let p1 = BigInt(1000000000) * BigInt(123456789) + BigInt(123456789)
, p2 = BigInt(1000000000) * BigInt(987654321) + BigInt(987654321)
;
console.log(`standard: =${123456789 * 987654321}`);
console.log(`standard large: =${123456789123456789 * 987654321987654321}`);
console.log(`BigInt: =${p1 * p2}`);

Related

Randomize multiple integers to equal variable

Using JavaScript, how would I go about generating 30 random integers and have the sum of those 30 integers be 60000? I need the script to produce a different set of numbers each time it is run, making sure that the total is always 60000
var n = 30;
var total = 60000;
var min = 10;
var max = 5000;
for (i = 0; i < n; i++) {
// Math.floor(Math.random()*(max-min+1)+min); ??
}
In order to avoid excessively large and small numbers, the min and max values will likely be needed
You can try something like this:
Logic
Accept Max total and total number of resulting Numbers.
Now loop based on this number - 1 for n-1 random numbers and last value should be max - currentSum. Since rest of numbers are random, this difference will also be random and this will also ensure total being equal.
Now all you need to do is return a random number based on a given range.
I have also added a flag to check for unique values. Currently I have just added 1 to it but this will not ensure its uniqueness, but as its out of scope, not rectifying it.
Code
function getRandomInRange(max) {
var raiseVal = Math.pow(10, (max.toString().length - 1) || 1);
return Math.floor(Math.random() * raiseVal) % max;
}
function getRandomNumbers(max, n, uniqueNum) {
var nums = [];
var sum = 0;
for (var i = 0; i < n - 1; i++) {
let r = getRandomInRange(max - sum);
if(uniqueNum && nums.indexOf(r) > -1){
r += 1;
}
nums.push(r)
sum += r;
}
nums.push(max - sum);
console.log(nums)
return nums
}
getRandomNumbers(3, 3, true)
getRandomNumbers(3, 3)
getRandomNumbers(1000, 10)
getRandomNumbers(600000, 30)

Using arrays to do basic calculations with negative exponent

I'm trying to write a function which outputs the correct result when multiplying a number by a negative power of ten using arrays and split() method. For example the following expressions get the right result: 1x10^-2 = 0.01 1x10^-4 = 0.0001.
Problem comes when the number's length is superior to the exponent value (note that my code treats num as a string to split it in an array as shown in code bellow :
//var num is treated as a string to be splited inside get_results() function
//exponent is a number
//Try different values for exponent and different lengths for num to reproduce the problem
//for example var num = 1234 and var exponent = 2 will output 1.234 instead of 12.34
var num = '1';
var sign = '-';
var exponent = 2;
var op = 'x10^'+sign+exponent;
var re = get_result(num);
console.log(num+op +' = '+ re);
function get_result(thisNum) {
if (sign == '-') {
var arr = [];
var splitNum = thisNum.split('');
for (var i = 0; i <= exponent-splitNum.length; i++) {
arr.push('0');
}
for (var j = 0; j < splitNum.length; j++) {
arr.push(splitNum[j]);
}
if (exponent > 0) {
arr.splice(1, 0, '.');
}
arr.join('');
}
return arr.join('');
}
Demo here : https://jsfiddle.net/Hal_9100/c7nobmnj/
I tried different approaches to get the right results with different num lengths and exponent values, but nothing I came with worked and I came to the point where I can't think of anything else.
You can see my latest try here : https://jsfiddle.net/Hal_9100/vq1hrru5/
Any idea how I could solve this problem ?
PS: I know most of the rounding errors due to javascript floating point conversion are pretty harmless and can be fixed using toFixed(n) or by using specialized third-party librairies, but my only goal here is to get better at writing pure javascript functions.
I am not sure if you want to keep going with the array approach to a solution, but it seems like this could be solved with using the Math.pow() method that already exists.
function computeExponentExpression ( test ) {
var base;
var multiplier;
var exponent;
test.replace(/^(\d+)(x)(\d+)([^])([-]?\d+)$/, function() {
base = parseInt(arguments[1], 10);
multiplier = parseInt(arguments[3], 10);
exponent = parseInt(arguments[5], 10);
return '';
} );
console.log( base * Math.pow(multiplier, exponent));
}
computeExponentExpression('1x10^-4');
computeExponentExpression('1x10^2');
computeExponentExpression('4x5^3');
The problem is where you push the decimal point .
instead of
arr.splice(1, 0, '.');
try this:
arr.splice(-exponent, 0, '.');
See fiddle: https://jsfiddle.net/free_soul/c7nobmnj/1/

Codefights: Correct solution but system does not accept it

Experienced codefighters, i have just started using Codefight website to learn Javascript. I have solved their task but system does not accept it. The task is to sum all integers (inidividual digit) in a number. For example sumDigit(111) = 3. What is wrong with my code? Please help me.
Code
function digitSum(n) {
var emptyArray = [];
var total = 0;
var number = n.toString();
var res = number.split("");
for (var i=0; i<res.length; i++) {
var numberInd = Number(res[i]);
emptyArray.push(numberInd);
}
var finalSum = emptyArray.reduce(add,total);
function add(a,b) {
return a + b;
}
console.log(finalSum);
//console.log(emptyArray);
//console.log(res);
}
Here's a faster trick for summing the individual digits of a number using only arithmetic:
var digitSum = function(n) {
var sum = 0;
while (n > 0) {
sum += n % 10;
n = Math.floor(n / 10);
}
return sum;
};
n % 10 is the remainder when you divide n by 10. Effectively, this retrieves the ones-digit of a number. Math.floor(n / 10) is the integer division of n by 10. You can think of it as chopping off the ones-digit of a number. That means that this code adds the ones digit to sum, chops off the ones digit (moving the tens digit down to where the ones-digit was) and repeats this process until the number is equal to zero (i.e. there are no digits left).
The reason why this is more efficient than your method is that it doesn't require converting the integer to a string, which is a potentially costly operation. Since CodeFights is mainly a test of algorithmic ability, they are most likely looking for the more algorithmic answer, which is the one I explained above.

Var overflow in JS and mongo [duplicate]

In JavaScript I would like to create the binary hash of a large boolean array (54 elements) with the following method:
function bhash(arr) {
for (var i = 0, L = arr.length, sum = 0; i < L; sum += Math.pow(2,i)*arr[i++]);
return sum;
}
In short: it creates the smallest integer to store an array of booleans in. Now my problem is that javascript apparently uses floats as default. The maximum number I have to create is 2^54-1 but once javascript reaches 2^53 it starts doing weird things:
9007199254740992+1 = 9007199254740994
Is there any way of using integers instead of floats in javascript? Or large integer summations?
JavaScript uses floating point internally.
What is JavaScript's highest integer value that a number can go to without losing precision?
In other words you can't use more than 53 bits. In some implementations you may be limited to 31.
Try storing the bits in more than one variable, use a string, or get a bignum library, or if you only need to deal with integers, a biginteger library.
BigInt is being added as a native feature of JavaScript.
typeof 123;
// → 'number'
typeof 123n;
// → 'bigint'
Example:
const max = BigInt(Number.MAX_SAFE_INTEGER);
const two = 2n;
const result = max + two;
console.log(result);
// → '9007199254740993'
javascript now has experimental support for BigInt.
At the time of writing only chrome supports this.
caniuse has no entry yet.
BigInt can be either used with a constructor, e.g. BigInt(20) or by appending n, e.g. 20n
Example:
const max = Number.MAX_SAFE_INTEGER;
console.log('javascript Number limit reached', max + 1 === max + 2) // true;
console.log('javascript BigInt limit reached', BigInt(max) + 1n === BigInt(max) + 2n); // false
No. Javascript only has one numeric type. You've to code yourself or use a large integer library (and you cannot even overload arithmetic operators).
Update
This was true in 2010... now (2019) a BigInt library is being standardized and will most probably soon arrive natively in Javascript and it will be the second numeric type present (there are typed arrays, but - at least formally - values extracted from them are still double-precision floating point numbers).
Another implementation of large integer arithmetic (also using BigInt.js) is available at www.javascripter.net/math/calculators/100digitbigintcalculator.htm. Supports the operations + - * / as well as remainder, GCD, LCM, factorial, primality test, next prime, previous prime.
So while attempting one of the leetcode problem I have written a function which takes two numbers in form of string and returns the sum of those numbers in form of string.
(This doesn't work with negative numbers though we can modify this function to cover that)
var addTwoStr = function (s1, s2) {
s1 = s1.split("").reverse().join("")
s2 = s2.split("").reverse().join("")
var carry = 0, rS = '', x = null
if (s1.length > s2.length) {
for (let i = 0; i < s1.length; i++) {
let s = s1[i]
if (i < s2.length) {
x = Number(s) + Number(s2[i]) + carry
rS += String((x % 10))
carry = parseInt(x/10)
} else {
if (carry) {
x = Number(s) + carry
rS += String((x % 10))
carry = parseInt(x/10)
} else {
rS += s
}
}
}
} else {
for (let i = 0; i < s2.length; i++) {
let s = s2[i]
if (i < s1.length) {
x = Number(s) + Number(s1[i]) + carry
rS += String((x % 10))
carry = parseInt(x/10)
} else {
if (carry) {
x = Number(s) + carry
rS += String((x % 10))
carry = parseInt(x/10)
} else {
rS += s
}
}
}
}
if (carry) {
rS += String(carry)
}
return rS.split("").reverse().join("")
}
Example: addTwoStr('120354566', '321442535')
Output: "441797101"
There are various BigInteger Javascript libraries that you can find through googling. e.g. http://www.leemon.com/crypto/BigInt.html
Here's (yet another) wrapper around Leemon Baird's BigInt.js
It is used in this online demo of a big integer calculator in JavaScript which implements the usual four operations + - * /, the modulus (%), and four builtin functions : the square root (sqrt), the power (pow), the recursive factorial (fact) and a memoizing Fibonacci (fibo).
You're probably running into a byte length limit on your system. I'd take the array of booleans, convert it to an array of binary digits ([true, false, true] => [1,0,1]), then join this array into a string "101", then use parseInt('101',2), and you'll have your answer.
/** --if you want to show a big int as your wish use install and require this module
* By using 'big-integer' module is easier to use and handling the big int numbers than regular javascript
* https://www.npmjs.com/package/big-integer
*/
let bigInt = require('big-integer');
//variable: get_bigInt
let get_bigInt = bigInt("999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999");
let arr = [1, 100000, 21, 30, 4, BigInt(999999999999), get_bigInt.value];
console.log(arr[6]); // Output: 999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999n
//Calculation
console.log(arr[6] + 1n); // +1
console.log(arr[6] + 100n); // +100
console.log(arr[6] - 1n); // -1
console.log(arr[6] - 10245n); // -1000n
console.log((arr[6] * 10000n) + 145n - 435n);

Javascript bitshift alternative to math.round

var1=anyInteger
var2=anyInteger
(Math.round(var1/var2)*var2)
What would be the syntax for JavaScripts bitshift alternative for the above?
Using integer not floating
Thank you
[UPDATED]
The quick answer:
var intResult = ((((var1 / var2) + 0.5) << 1) >> 1) * var2;
It's faster than the Math.round() method provided in the question and provides the exact same values.
Bit-shifting is between 10 and 20% faster from my tests. Below is some updated code that compares the two methods.
The code below has four parts: first, it creates 10,000 sets of two random integers; second, it does the round in the OP's question, stores the value for later comparison and logs the total time of execution; third, it does an equivalent bit-shift, stored the value for later comparison, and logs the execution time; fourth, it compares the Round and Bit-shift values to find any differences. It should report no anomalies.
Note that this should work for all positive, non-zero values. If the code encounters a zero for the denominator, it will raise and error, and I'm pretty sure that negative values will not bit-shift correctly, though I've not tested.
var arr1 = [],
arr2 = [],
arrFloorValues = [],
arrShiftValues = [],
intFloorTime = 0,
intShiftTime = 0,
mathround = Math.round, // #trinithis's excellent suggestion
i;
// Step one: create random values to compare
for (i = 0; i < 100000; i++) {
arr1.push(Math.round(Math.random() * 1000) + 1);
arr2.push(Math.round(Math.random() * 1000) + 1);
}
// Step two: test speed of Math.round()
var intStartTime = new Date().getTime();
for (i = 0; i < arr1.length; i++) {
arrFloorValues.push(mathround(arr1[i] / arr2[i]) * arr2[i]);
}
console.log("Math.floor(): " + (new Date().getTime() - intStartTime));
// Step three: test speed of bit shift
var intStartTime = new Date().getTime();
for (i = 0; i < arr1.length; i++) {
arrShiftValues.push( ( ( ( (arr1[i] / arr2[i]) + 0.5) << 1 ) >> 1 ) * arr2[i]);
}
console.log("Shifting: " + (new Date().getTime() - intStartTime));
// Step four: confirm that Math.round() and bit-shift produce same values
intMaxAsserts = 100;
for (i = 0; i < arr1.length; i++) {
if (arrShiftValues[i] !== arrFloorValues[i]) {
console.log("failed on",arr1[i],arr2[i],arrFloorValues[i],arrShiftValues[i])
if (intMaxAsserts-- < 0) break;
}
}
you should be able to round any number by adding 0.5 then shifting off the decimals...
var anyNum = 3.14;
var rounded = (anyNum + 0.5) | 0;
so the original expression could be solved using this (instead of the slower Math.round)
((var1/var2 + 0.5)|0) * var2
Run the code snippet below to test different values...
function updateAnswer() {
var A = document.getElementById('a').value;
var B = document.getElementById('b').value;
var h = "Math.round(A/B) * B = <b>" + (Math.round(A/B) * B) + "</b>";
h += "<br/>";
h += "((A/B + 0.5)|0) * B = <b>" + ((A/B + 0.5) | 0) * B +"</b>";
document.getElementById('ans').innerHTML = h;
}
*{font-family:courier}
A: <input id="a" value="42" />
<br/>
B: <input id="b" value="7" />
<br/><br/>
<button onclick="updateAnswer()">go</button>
<hr/>
<span id="ans"></span>
If var2 is a power of two (2^k) you may
write
(var1>>k)<<k
but in the general case
there is no straightforward solution.
You can do (var | 0) - that would truncate the number to an integer, but you'll always get the floor value. If you want to round it, you'll need an additional if statement, but in this case Math.round would be faster anyway.
Unfortunately, bit shifting operations usually only work with integers. Are your variables integers or floats?

Categories