Split a whole number into fractions, find which of thoses fractions another belongs in

254 Views Asked by At

I want to split a number into $n$ parts and then take another number (which is less than or equal to the first number) and see which of the fractions the other number belongs to.

For example, split $100$ into $4$ parts. Which part does $36$ belong to? The second part, $26-50$.

For the record, I'm going to be using this in JavaScript so pseudo-code would be great but not required.

2

There are 2 best solutions below

2
On BEST ANSWER

Perhaps something like this?

function returnNthPart(value,max,nparts){
    return Math.ceil(nparts*value/max);
}
0
On

There is an $\mathcal{O}(1)$ solution to this problem, if $n$ signifies the section that it belongs to, and $N$ is the initial number

$$n=\left\lceil\frac{N \cdot k}{q}\right\rceil,$$

Where $k$ is the initial number (in your case $100$) and $q$ is the number of parts. In JavaScript this would be something like:

function divisionSection( value, initialNumber, numParts ) {
      return Math.ceil( value * initialNumber / numParts ); 
}