I need to separate an integer into two numbers. Something like dividing by two but I only want integer components as a result, such as:
6 = 3 and 3 7 = 4 and 3
I tried the following, but I'm not sure its the best solution.
var number = 7; var part1 = 0; var part2 = 0; if((number % 2) == 0) { part1 = number / 2; part2 = number / 2; } else { part1 = parseInt((number / 2) + 1); part2 = parseInt(number / 2); }
This does what I want, but I don't think this code is clean.
Are there better ways of doing this?
Approach: There is always a way of splitting the number if X >= N. If the number is being split into exactly 'N' parts then every part will have the value X/N and the remaining X%N part can be distributed among any X%N numbers.
Function divideN(int n) takes n and returns the number of ways in which n can be divided into 3 parts. Take the initial variable count as 0 for the number of ways. Traverse using three for loops for each part of the number. Outermost loop from 1<=i<n, inner loop i<=j<n , innermost j<=k<n.
We can use the len() method and get half of the string. We then use the slice notation technique to slice off the first and second of the string value to store the then in separate variables.
Just find the first part and subtract it from the original number.
var x = 7; var p1 = Math.floor(x / 2); var p2 = x - p1; console.log(p1, p2);
In the case of x
being odd, p1
will receive the smaller of the two addends. You can switch this around by calling Math.ceil
instead.
Let javascript do Math for you.
var x = 7; var p1 = Math.ceil(x / 2); var p2 = Math.floor(x / 2); console.log(p1, p2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With