Click here to Skip to main content
15,890,897 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello
please give me any solution
if i divide 100 by 30 then answer is 3.3333 but i want 10/3
Posted

You are looking for the greatest common divisor of the numbers, and then divide the numbers by that GCD. There is a built-in method for this in the System.Numerics.BigInteger class (you'll need to add a reference to System.Numerics before you can use it). Add this on the top of your code file, after adding a reference to System.Numerics:
C#
using System.Numerics;

And then, use this code:
C#
string input = "100/30";
string[] numbers = input.Split('/');
int numerator;
int denominator;
if (numbers.Length == 2 && int.TryParse(numbers[0], out numerator) && int.TryParse(numbers[1], out denominator))
{
    BigInteger gcd = BigInteger.GreatestCommonDivisor(new BigInteger(numerator), new BigInteger(denominator));
    int gcdInt = (int)gcd;
    int newNumerator = numerator / gcdInt;
    int newDenominator = denominator / gcdInt;
    string result = String.Concat(newNumerator, "/", newDenominator);
}
else
{
    // invalid input
}
 
Share this answer
 
v2
Hi,


You can reach your goal by Find "GCF (Greatest Common Factor)" for two numbers.


Divide both number by its GCF

Function for Find GCF

C#
int GCF(int a, int b)
        {
            int Remainder;

            while (b != 0)
            {
                Remainder = a % b;
                a = b;
                b = Remainder;
            }

            return a;
        }


Then Your Result is

C#
<pre>int a=100, b=30;

int gcf = GCF(a,b);

lblResult.Text = (a / gcf) + &quot;/&quot; + (b / gcf);

</pre>


Result : 10 / 3

Thanks

Siva Rm K
 
Share this answer
 
What you need is a fractions class

Fortunately someone wrote one[^]
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 10-Nov-14 8:37am    
5ed. Only the proper name for such object would be "rational number".
—SA
Maciej Los 10-Nov-14 10:15am    
+5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900