Through applying a computer science algorithm in JavaScript, could you solve the following question?
The function accepts a numerator and denominator in the form of a positive or negative integer value.
You can not use '*', '/' or '%'.
function divide(num, denom) {
// ...
}
divide(6, 2)
divide(-10, 5)
divide(7, 2)
divide(-5, 10)
I am curious to know if there is a known computer science algorithm out there that can solve this.
I saw this question and had to take a crack at it, I've implemented a solution that can get decimal places up to a specified precision as well as handle negatives, it uses a recursive approach and some string manipulation.
// Calculate up to decimal point
const MAX_PRECISION = 6;
function divide(numerator, denominator, answer=0, decimals=MAX_PRECISION)
{
// Account for negative numbers
if ((numerator < 0 || denominator < 0))
{
// If both are negative, then we return a positive, otherwise return a negative
if (numerator < 0 && denominator < 0)
return divide(Math.abs(numerator), Math.abs(denominator))
else return -divide(Math.abs(numerator), Math.abs(denominator));
}
// Base case return if evenly divisble or we've reached the specificed percision
if (numerator == 0 || decimals == 0) return answer;
// Calculate the decimal places
if (numerator < denominator)
{
// Move the decinal place to the right
const timesTen = parseInt(numerator + "0");
// Calcualte decimal places up to the certain percision
if (decimals == MAX_PRECISION)
return parseFloat(answer + "." + divide(timesTen, denominator, 0, decimals-1));
else return answer + "" + divide(timesTen, denominator, 0, decimals-1);
}
// Perform the calculations in a tail-recursive manor
return divide(numerator-denominator, denominator, answer+1, decimals);
}
// Test Cases
console.log(divide(10, 2));
console.log(divide(10, -2));
console.log(divide(-7, -4));
console.log(divide( 1, -2));
console.log(divide(11, 3));
console.log(divide(22, 7));
You can try Something like:
function divide(num, denom) {
var count = 0;
while (num > 0) {
num = num - denom
if (num >= 0) {
count ++;
}
}
return count;
}
For a homework assignment, I need to return the remainder after dividing num1 by num2 WITHOUT using the built-in modulo (%) operator. I'm able to get most tests to pass with the following code, but I'm stuck on how to account for -/+ signs of the given numbers. I need to carry over whichever sign is on num1, and also return a positive number if the num2 is negative - it's blowing my mind how to do this... :) Any clarity would be greatly appreciated! I'm not exactly looking for the straight up answer here, more that I seem to be missing something obvious... Maybe I need a new approach?
function modulo(num1, num2) {
if (num1 === 0) {
return 0;
}
if (num2 === 0 || isNaN(num1) || isNaN(num2)) {
return NaN;
}
if (num1 < num2) {
return num1;
}
if (num1 > 0 && num2 > 0) {
var counter = num1;
while (counter >= Math.abs(num2)) {
counter = counter - num2;
}
return counter;
}
}
var output = modulo(25, 4);
console.log(output); // 1
If you think about the mathematical process to calculate modulus you might be able see how you can do this without having to resort to a bunch of case statements. Instead think of it this way, you're just calculating a remainder:
Given 2 numbers a and b, you can compute mod(a,b) by doing the following:
q = a / b; //finding quotient (integer part only)
p = q * b; //finding product
remainder = a - p; //finding modulus
Using this idea, you should be able to transfer it to JS. You said you're not looking for the straight up answer so that's all I'll say!
Edit: here is the code, like I said in the comments it's exactly the pseudocode I posted above:
function modulo(a,b){
q = parseInt(a / b); //finding quotient (integer part only)
p = q * b; //finding product
return a - p; //finding modulus
}
This will return the exact same values as using %
You might be overthinking this. You basically stated the solution in your question:
I need to carry over whichever sign is on num1, and also return a positive number if the num2 is negative
The second part isn't accurate, but I suspect you just misspoke. A positive number should be returned when num2 is negative unless num1 is negative.
At any rate, the important takeaway is that if num1 is negative the result will be negative, and otherwise the result will be positive. The sign of num2 is discarded.
Starting the code you've written (which others will be quick to point out isn't the simplest solution), the fix is to compute the remainder using both numbers' absolute values, and then apply num1's original sign to the result.
function modulo(num1, num2) {
var sign = num1 < 0 ? -1 : 1;
var dividend = Math.abs(num1);
var divisor = Math.abs(num2);
if (dividend === 0) {
return 0;
}
if (dividend === 0 || isNaN(dividend) || isNaN(divisor)) {
return NaN;
}
if (dividend < divisor) {
return sign * dividend;
}
var counter = dividend;
while (counter >= divisor) {
counter = counter - divisor;
}
return sign * counter;
}
console.log( 25 % 4, modulo( 25, 4));
console.log(-25 % 4, modulo(-25, 4));
console.log( 25 % -4, modulo( 25, -4));
console.log(-25 % -4, modulo(-25, -4));
.as-console-wrapper{min-height:100%;}
This is the basic formula:
dividend = divisor * quotient + remainder
From this equation you can calculate the remainder.
I need a function that generates a completely random integer (very important) within a user specified number range (between -9999 to 9999) and a user specified digit limit (between 1 and 4 digits).
Example 1: If the user wants a number between -9999 and 9999 that's 4 digits, the following numbers would be eligible choices -9999 to -1000 and 1000 to 9999.
Example 2: If the user wants a number between 25 and 200 that's 2 OR 3 digits, the following numbers would be eligible choices 25 to 200.
I wrote a function that works but I am not sure if it's the best solution? There's duplicate code and I don't think it's completely random?
// Generates a random integer
// Number range
// Min (-9999-9999)
// Max (-9999-9999)
// Digit limit
// Min (1-4)
// Max (1-4)
function generateRandomInteger(minNumber, maxNumber, minDigits, maxDigits) {
// Generate a random integer in the number range
var num = Math.floor(Math.random() * (maxNumber - minNumber)) + minNumber;
// Find number of digits
var n = num.toString();
n = n.length;
// If number is negative subtract 1 from length because of "-" sign
if (num < 0) {
n--;
}
// End: find number of digits
while ((n > maxDigits) || (n < minDigits)) {
// Generate a random integer in the number range
num = Math.floor(Math.random() * (maxNumber - minNumber)) + minNumber;
// Find number of digits
var n = num.toString();
n = n.length;
// If number is negative subtract 1 from length because of "-" sign
if (num < 0) {
n--;
}
// End: find number of digits
}
return num;
}
Well here's a version of your function that still uses exactly the same method (i.e., keeps generating numbers until it gets one with the right number of digits), but with the code duplication eliminated:
function generateRandomInteger(minNumber, maxNumber, minDigits, maxDigits) {
var num, digits;
do {
num = Math.floor(Math.random() * (maxNumber - minNumber)) + minNumber;
digits = Math.abs(num).toString().length;
} while (digits > maxDigits || digits < minDigits);
return num;
}
As for your concern about whether this is really random, the Math.random() method will give you a "pseudo-random" number, but at least you know it will work in all current browsers.
Try this functional approach, it creates an array and shuffles it randomly so it gives "very random" results. I've used it before with very satisfying results.
function getLen( v ) {
return Math.abs( v ).toString().length;
};
function randomInteger( min, max ) {
return ( new Array( ++max - min ) )
.join('.').split('.')
.map(function( v,i ){ return [ Math.random(), min + i ] })
.filter(function( v ){ return getLen( v[1] ) >= getLen( min ) })
.sort().map(function( v ) { return v[1] }).pop();
}
I need to round for example 6.688689 to 6.7, but it always shows me 7.
My method:
Math.round(6.688689);
//or
Math.round(6.688689, 1);
//or
Math.round(6.688689, 2);
But result always is the same 7... What am I doing wrong?
Number((6.688689).toFixed(1)); // 6.7
var number = 6.688689;
var roundedNumber = Math.round(number * 10) / 10;
Use toFixed() function.
(6.688689).toFixed(); // equal to "7"
(6.688689).toFixed(1); // equal to "6.7"
(6.688689).toFixed(2); // equal to "6.69"
Upd (2019-10). Thanks to Reece Daniels code below now available as a set of functions packed in npm-package expected-round (take a look).
You can use helper function from MDN example. Than you'll have more flexibility:
Math.round10(5.25, 0); // 5
Math.round10(5.25, -1); // 5.3
Math.round10(5.25, -2); // 5.25
Math.round10(5, 0); // 5
Math.round10(5, -1); // 5
Math.round10(5, -2); // 5
Upd (2019-01-15). Seems like MDN docs no longer have this helper funcs. Here's a backup with examples:
// Closure
(function() {
/**
* Decimal adjustment of a number.
*
* #param {String} type The type of adjustment.
* #param {Number} value The number.
* #param {Integer} exp The exponent (the 10 logarithm of the adjustment base).
* #returns {Number} The adjusted value.
*/
function decimalAdjust(type, value, exp) {
// If the exp is undefined or zero...
if (typeof exp === 'undefined' || +exp === 0) {
return Math[type](value);
}
value = +value;
exp = +exp;
// If the value is not a number or the exp is not an integer...
if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
return NaN;
}
// If the value is negative...
if (value < 0) {
return -decimalAdjust(type, -value, exp);
}
// Shift
value = value.toString().split('e');
value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
// Shift back
value = value.toString().split('e');
return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
}
// Decimal round
if (!Math.round10) {
Math.round10 = function(value, exp) {
return decimalAdjust('round', value, exp);
};
}
// Decimal floor
if (!Math.floor10) {
Math.floor10 = function(value, exp) {
return decimalAdjust('floor', value, exp);
};
}
// Decimal ceil
if (!Math.ceil10) {
Math.ceil10 = function(value, exp) {
return decimalAdjust('ceil', value, exp);
};
}
})();
Usage examples:
// Round
Math.round10(55.55, -1); // 55.6
Math.round10(55.549, -1); // 55.5
Math.round10(55, 1); // 60
Math.round10(54.9, 1); // 50
Math.round10(-55.55, -1); // -55.5
Math.round10(-55.551, -1); // -55.6
Math.round10(-55, 1); // -50
Math.round10(-55.1, 1); // -60
Math.round10(1.005, -2); // 1.01 -- compare this with Math.round(1.005*100)/100 above
Math.round10(-1.005, -2); // -1.01
// Floor
Math.floor10(55.59, -1); // 55.5
Math.floor10(59, 1); // 50
Math.floor10(-55.51, -1); // -55.6
Math.floor10(-51, 1); // -60
// Ceil
Math.ceil10(55.51, -1); // 55.6
Math.ceil10(51, 1); // 60
Math.ceil10(-55.59, -1); // -55.5
Math.ceil10(-59, 1); // -50
> +(6.688687).toPrecision(2)
6.7
A Number object in JavaScript has a method that does exactly what you need. That method is Number.toPrecision([precision]).
Just like with .toFixed(1) it converts the result into a string, and it needs to be converted back into a number. Done using the + prefix here.
simple benchmark on my laptop:
number = 25.645234 typeof number
50000000 x number.toFixed(1) = 25.6 typeof string / 17527ms
50000000 x +(number.toFixed(1)) = 25.6 typeof number / 23764ms
50000000 x number.toPrecision(3) = 25.6 typeof string / 10100ms
50000000 x +(number.toPrecision(3)) = 25.6 typeof number / 18492ms
50000000 x Math.round(number*10)/10 = 25.6 typeof number / 58ms
string = 25.645234 typeof string
50000000 x Math.round(string*10)/10 = 25.6 typeof number / 7109ms
If you not only want to use toFixed() but also ceil() and floor() on a float then you can use the following function:
function roundUsing(func, number, prec) {
var tempnumber = number * Math.pow(10, prec);
tempnumber = func(tempnumber);
return tempnumber / Math.pow(10, prec);
}
Produces:
> roundUsing(Math.floor, 0.99999999, 3)
0.999
> roundUsing(Math.ceil, 0.1111111, 3)
0.112
UPD:
The other possible way is this:
Number.prototype.roundUsing = function(func, prec){
var temp = this * Math.pow(10, prec)
temp = func(temp);
return temp / Math.pow(10, prec)
}
Produces:
> 6.688689.roundUsing(Math.ceil, 1)
6.7
> 6.688689.roundUsing(Math.round, 1)
6.7
> 6.688689.roundUsing(Math.floor, 1)
6.6
My extended round function:
function round(value, precision) {
if (Number.isInteger(precision)) {
var shift = Math.pow(10, precision);
// Limited preventing decimal issue
return (Math.round( value * shift + 0.00000000000001 ) / shift);
} else {
return Math.round(value);
}
}
Example Output:
round(123.688689) // 123
round(123.688689, 0) // 123
round(123.688689, 1) // 123.7
round(123.688689, 2) // 123.69
round(123.688689, -2) // 100
round(1.015, 2) // 1.02
See below
var original = 28.59;
var result=Math.round(original*10)/10 will return you returns 28.6
Hope this is what you want..
There is the alternative .toLocaleString() to format numbers, with a lot of options regarding locales, grouping, currency formatting, notations. Some examples:
Round to 1 decimal, return a float:
const n = +6.688689.toLocaleString('fullwide', {maximumFractionDigits:1})
console.log(
n, typeof n
)
Round to 2 decimals, format as currency with specified symbol, use comma grouping for thousands:
console.log(
68766.688689.toLocaleString('fullwide', {maximumFractionDigits:2, style:'currency', currency:'USD', useGrouping:true})
)
Format as locale currency:
console.log(
68766.688689.toLocaleString('fr-FR', {maximumFractionDigits:2, style:'currency', currency:'EUR'})
)
Round to minimum 3 decimal, force zeroes to display:
console.log(
6.000000.toLocaleString('fullwide', {minimumFractionDigits:3})
)
Percent style for ratios. Input * 100 with % sign
console.log(
6.688689.toLocaleString('fullwide', {maximumFractionDigits:2, style:'percent'})
)
I have very good solution with if toFixed() is not working.
function roundOff(value, decimals) {
return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}
Example
roundOff(10.456,2) //output 10.46
float(value,ndec);
function float(num,x){
this.num=num;
this.x=x;
var p=Math.pow(10,this.x);
return (Math.round((this.num).toFixed(this.x)*p))/p;
}
+((6.688689 * (1 + Number.EPSILON)).toFixed(1)); // 6.7
+((456.1235 * (1 + Number.EPSILON)).toFixed(3)); // 456.124
I think this function can help.
function round(value, ndec){
var n = 10;
for(var i = 1; i < ndec; i++){
n *=10;
}
if(!ndec || ndec <= 0)
return Math.round(value);
else
return Math.round(value * n) / n;
}
round(2.245, 2) //2.25
round(2.245, 0) //2
if you're under node.js context, you can try mathjs
const math = require('mathjs')
math.round(3.1415926, 2)
// result: 3.14
Math.round((6.688689 + Number.EPSILON) * 10) / 10
Solution stolen from https://stackoverflow.com/a/11832950/2443681
This should work with nearly any float value. It doesn't force decimal count though. It's not clear whether this was a requirement. Should be faster than using toFixed(), which has other issues as well based on the comments to other answers.
A nice utility function to round in needed decimal precision:
const roundToPrecision = (value, decimals) => {
const pow = Math.pow(10, decimals);
return Math.round((value + Number.EPSILON) * pow) / pow;
};
I think below function can help
function roundOff(value,round) {
return (parseInt(value * (10 ** (round + 1))) - parseInt(value * (10 ** round)) * 10) > 4 ? (((parseFloat(parseInt((value + parseFloat(1 / (10 ** round))) * (10 ** round))))) / (10 ** round)) : (parseFloat(parseInt(value * (10 ** round))) / ( 10 ** round));
}
usage : roundOff(600.23458,2); will return 600.23
Minor tweak to this answer:
function roundToStep(value, stepParam) {
var step = stepParam || 1.0;
var inv = 1.0 / step;
return Math.round(value * inv) / inv;
}
roundToStep(2.55, 0.1) = 2.6
roundToStep(2.55, 0.01) = 2.55
roundToStep(2, 0.01) = 2
How to correctly round decimals in a number (basics):
We start from far right number:
If this number is >= to 5 rounding is required, we will then report a 1 to the first number on the left.
If this number is < to 5 means no rounding
Once you know if you need to report a value or not you can delete the last number and repeat the operation.
If there is a value to be reported you will first add it to the new far right number before repeating the previous tests.
Beware there is a special case when you need to report a value and the number that must be added to that value is 9 : in such case you will have to change the number value for 0 before reporting a 1 on the following left number.
For some of the failing answers it looks like decimals are splitted left to right for the required amount of decimals without even caring about the rounding.
Now that this is stated here is a function that will round a provided float value recursively using the above logic.
function roundFloatR(n, precision = 0, opts = { return: 'number' }) { // Use recursivity
if ( precision == 0 ) { // n will be rounded to the closest integer
if (opts.return == 'number') return Math.round(n);
else if (opts.return == 'string') return `${Math.round(n)}`;
} else {
let ns = `${n}`.split(''); // turns float into a string before splitting it into a char array
if ( precision < 0 ) { // precision is a negative number
precision += ns.length - 1; // precision equals last index of ns - its actual value
} else if ( precision > 0 ) { // precision is a positive number
if ( ns.indexOf('.') > -1 )
precision += ns.indexOf('.'); // precision equals its value + the index of the float separator in the string / array of char
}
// RECURSIVE FUNCTION: loop from the end of ns to the precision index while rounding the values
// index: index in the ns char array, rep: reported value, (INTERNAL_VAR, cn: current number)
const recursive = (index, rep) => {
let cn = parseInt(ns[index]); // get the current number from ns at index
if (index <= precision) { // current index inferior or equal to the defined precision index (end of rounding)
if (rep) { // if a reported value exists
cn += rep; // add reported value to current number
if (cn == 10) { // extends rounding for special case of decimals ending with 9 + reported value
ns[index] = '0';
recursive( (index - 1), 1 ); // calls recursive() again with a reported value
} else if (cn < 10)
ns[index] = `${cn}`;
}
} else if (index > precision) { // current index superior to defined precision index
ns.pop(); // each passage in this block will remove the last entry of ns
if (rep) cn += rep; // adds reported value (if it exists) to current number
if ( cn >= 5 ) // ROUNDING
recursive( (index - 1), 1 ); // calls recursive() again with a reported value
else // NO ROUNDING
recursive( index - 1 ); // calls recursive() again w/o a reported value
}
}; // end of recursive()
recursive(ns.length - 1); // starts recursive rounding over the ns char array (arg is the last index of ns)
if (opts.return == "number") return parseFloat(ns.join('')); // returns float number
else if (opts.return == "string") return ns.join(''); // returns float number as string
}
} //
How it works:
We first turn the provided float value into a string before splitting it into an array of char using the String.split('') instruction.
Then we will call the recursive() function with the last index of the array of chars as argument, to iterate through that array from last index to the precision index while rounding the value.
Arguments explanation:
There is a total of 3 arguments which allow different functionnalities.
n:
the value to be rounded (number or string).
precision: [default = 0]
an int which represent the amount of decimals we want to round the provided number to.
There are 3 possibilities:
precision == 0: value returned will be the same as using the Math.round() method
precision > 0: precision will be defined from the float separator index + precision value
precision < 0: precision will be defined from the index of the last number - precision value
opts: [default = {return: 'number'}]
an options object with a unique property called return which take a string value options are 'number' or 'string'. allows the selection of the type of value returned by the function
2nd and 3rd arguments are optionnals
Usage and examples:
using a float value
let n = 20.336099982261654;
let r = roundFloatR(n); // r = 20
r = roundFloatR(n, 2); // r = 20.34
r = roundFloatR(n, 6); // r = 20.3361
r = roundFloatR(n, 6, {return: 'string'}); // r = "20.336100"
// negative precision
r = roundFloatR(n, -2); // r = 20.3360999822617
using a string value
let n = '20.48490002346038';
let r = roundFloatR(n); // r = 20
r = roundFloatR(n, 2); // r = 20.49
r = roundFloatR(n, 6); // r = 20.4849
r = roundFloatR(n, 6, {return: 'string'}); // r = "20.484900"
// negative precision
r = roundFloatR(n, -10); // r = 20.4849
What about performance ?
Most of the time it will convert the provided value in under .3 ms. (measured with performance.now())
What is not supported and possible issues:
not supported: exponential type values some changes may be required to support them.
possible issues:
a negative precision value that exceeds the provided number length or its float separator index may cause unexpected results as these cases are not handled yet.
no error handling in case the n parameter doesn't match what is currently asked.
If you're using Browserify today, you're going to have to try: roundTo a very useful NPM lib
I want to truncate a number in javascript, that means to cut away the decimal part:
trunc ( 2.6 ) == 2
trunc (-2.6 ) == -2
After heavy benchmarking my answer is:
function trunc (n) {
return ~~n;
}
// or
function trunc1 (n) {
return n | 0;
}
As an addition to the #Daniel's answer, if you want to truncate always towards zero, you can:
function truncate(n) {
return n | 0; // bitwise operators convert operands to 32-bit integers
}
Or:
function truncate(n) {
return Math[n > 0 ? "floor" : "ceil"](n);
}
Both will give you the right results for both, positive and negative numbers:
truncate(-3.25) == -3;
truncate(3.25) == 3;
For positive numbers:
Math.floor(2.6) == 2;
For negative numbers:
Math.ceil(-2.6) == -2;
You can use toFixed method that also allows to specify the number of decimal numbers you want to show:
var num1 = new Number(3.141592);
var num2 = num1.toFixed(); // 3
var num3 = num1.toFixed(2); // 3.14
var num4 = num1.toFixed(10); // 3.1415920000
Just note that toFixed rounds the number:
var num1 = new Number(3.641592);
var num2 = num1.toFixed(); // 4
I use
function trunc(n){
return n - n % 1;
}
because it works over the whole float range and should (not measured) be faster than
function trunc(n) {
return Math[n > 0 ? "floor" : "ceil"](n);
}
In case it wasn't available before and for anyone else who stumbles upon this thread, you can now simply use the trunc() function from the Math library, like so:
let x = -201;
x /= 10;
console.log(x);
console.log(Math.trunc(x));
>>> -20.1
>>> -20