1

Why does this code give me an answer of 25?

public int findGcd() {
    int num = this.num;
    int den = this.den;

    while (den != 0) {
        int t = den;
        den = num % den;
        num = t;
    }

    return num;
}

This is the main method:

public class FractionTest {
    public static void main(String args[]) {
        Fraction f = new Fraction();
        f.num = 25;
        f.den = 100;
        f.findGcd();
    }
}

Can anyone provide me a complete process of how all the program goes or run?

CSchulz
  • 10,882
  • 11
  • 60
  • 114
user759630
  • 679
  • 2
  • 8
  • 11

4 Answers4

3

Because gcd(25, 100) = 25 probably

Paweł Obrok
  • 22,568
  • 8
  • 74
  • 70
  • As this is probably a follow up to this [question](http://stackoverflow.com/questions/6882618/simplifying-fractions-with-java): Indeed 25 is the GCD. Now to simplify the fraction divide both the numerator and denominator by 25 and you get 1/4 instead of 25/100. Which is correct. – Mark Biesheuvel Aug 03 '11 at 10:24
2

It is called the Euclidean Algorithm.

Thilo
  • 257,207
  • 101
  • 511
  • 656
  • I know it's the Euclidean algorithm , I used the pseudocde there for my code, all I want is to have a complete explanation of how the program goes since I've been having a hard time with the modulo operator – user759630 Aug 03 '11 at 10:34
2

Here's a quick calculation you can also do by debugging your program to see how it works...

http://gcd.awardspace.com/?num1=25&num2=100&OG=on&SC=on&RF=on&RC=on

The link shows you how the calculation is done, if you can't see it yet. Hope this helps.

Whitebear
  • 1,761
  • 2
  • 12
  • 22
0

The while loop work like this

den!=0 100 != 0

inside loop

t = 25 (den)

0 = 25 % 100

num = 25 (t)

return 25 (num)

So the result is 25

nidhin
  • 6,661
  • 6
  • 32
  • 50