How to simplify a fraction in C#? For example, given 1 11/6
, I need it simplified to 2 5/6
.
If all you want is to turn your fraction into a mixed number whose fractional part is a proper fraction like the previous answers assumed, you only need to add numerator / denominator
to the whole part of the number and set the numerator to numerator % denominator
. Using loops for this is completely unnecessary.
However the term "simplify" usually refers to reducing a fraction to its lowest terms. Your example does not make clear whether you want that as well, as the example is in its lowest terms either way.
Here's a C# class that normalizes a mixed number, such that each number has exactly one representation: The fractional part is always proper and always in its lowest terms, the denominator is always positive and the sign of the whole part is always the same as the sign of the numerator.
using System;
public class MixedNumber {
public MixedNumber(int wholePart, int num, int denom)
{
WholePart = wholePart;
Numerator = num;
Denominator = denom;
Normalize();
}
public int WholePart { get; private set; }
public int Numerator { get; private set; }
public int Denominator { get; private set; }
private int GCD(int a, int b)
{
while(b != 0)
{
int t = b;
b = a % b;
a = t;
}
return a;
}
private void Reduce(int x) {
Numerator /= x;
Denominator /= x;
}
private void Normalize() {
// Add the whole part to the fraction so that we don't have to check its sign later
Numerator += WholePart * Denominator;
// Reduce the fraction to be in lowest terms
Reduce(GCD(Numerator, Denominator));
// Make it so that the denominator is always positive
Reduce(Math.Sign(Denominator));
// Turn num/denom into a proper fraction and add to wholePart appropriately
WholePart = Numerator / Denominator;
Numerator %= Denominator;
}
override public String ToString() {
return String.Format("{0} {1}/{2}", WholePart, Numerator, Denominator);
}
}
Sample usage:
csharp> new MixedNumber(1,11,6);
2 5/6
csharp> new MixedNumber(1,10,6);
2 2/3
csharp> new MixedNumber(-2,10,6);
0 -1/3
csharp> new MixedNumber(-1,-10,6);
-2 -2/3
int unit = 1;
int numerator = 11;
int denominator = 6;
while(numerator >= denominator)
{
numerator -= denominator;
if(unit < 0)
unit--;
else
unit++;
}
Then do whatever you like with the variables.
Note that this isn't particularly general.... in particular I doubt it's going to play well with negative numbers (edit: might be better now)
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