If I want to divide an odd number(for example 7) with 2 to 7, and I want a list of some integers.
if I divine 7 with 4, I should get {1, 2, 2, 2}, or if I divine 5 with 3, I want to get {1, 2, 2}.
How can I do this?
static List<int> OddNumDiv(int oddnum, int divnum)
{
List<int> result = new List<int>();
result.Add(oddnum / divnum);
int sum = 0;
for (int i = 0; i < divnum - 2; i++)
{
sum += (int)Math.Round((double)oddnum / divnum, MidpointRounding.AwayFromZero);
result.Add((int)Math.Round((double)oddnum / divnum, MidpointRounding.AwayFromZero));
}
result.Add(oddnum - sum);
return result;
}
static void Main(string[] args)
{
List<int> _7d4 = OddNumDiv(7, 4);
}
This returs with {1, 2, 2, 3} and not what I need {1, 2, 2, 2}
>Solution :
Don’t add rounded values to the sum. Always calculate the quotient and remainder separately for each division.
Below is the complete code for your desired solution.
public static List<int> OddNumDiv(int oddnum, int divnum)
{
List<int> result = new List<int>();
int quotient = oddnum / divnum; // Find the quotient when oddnum is divided by divnum
int remainder = oddnum % divnum; // Find the remainder when oddnum is divided by divnum
// Add quotient to the result list divnum-remainder times
for (int i = 0; i < divnum - remainder; i++)
{
result.Add(quotient);
}
// Add quotient+1 to the result list remainder times
for (int i = 0; i < remainder; i++)
{
result.Add(quotient + 1);
}
return result;
}
Here’s the relevant link to learn more about the modulo operator (%): https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/modulus-operator