1

Is there a function somewhere that divides integer or decimal numbers into parts that are as equal as possible and sum up to the input value?

I'm looking for something that would work like that:

devide(4,2) -> {2,2} (2+2=4, 2 and 2 are equal)

devide(6,4) -> {2,2,1,1} (2+2+1+1=6, no way to make these numbers closer to each other)

I know I can do it myself but I'm looking for some library function.

1
  • 1
    I don't know about any library with that functionality, but you should really implement it yourself. It's not that hard and adding a library to your project just for something that simple is a bad idea Commented Dec 28, 2018 at 12:04

1 Answer 1

2

I've never heard of a library that does that, but it'es quite easy. Just put the quotient in each cells of an array the size of the divisor, then put the remainder in each cell.

Example:

public static int[] divide(int n, int d){ //d for divisor
    int[] res = new int[d];
    int qu = n/d; //quotient
    int rm = n%d; //remainder 
    for(int i=0; i<d; i++){
        res[i] = qu;
        if(i  < rm){
            res[i]++;
        }
    }
    return res;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.