Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separate an integer into two (nearly) equal parts

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?

like image 245
Vash Avatar asked Jul 18 '17 10:07

Vash


People also ask

How do you divide a number into equal parts?

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.

How do you divide a number into equal parts in C++?

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.

How do you split a number in half in Python?

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.


2 Answers

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.

like image 68
cs95 Avatar answered Sep 20 '22 15:09

cs95


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);
like image 40
Suresh Atta Avatar answered Sep 23 '22 15:09

Suresh Atta