开发者

Java modulo operator and GCD

开发者 https://www.devze.com 2023-03-25 02:56 出处:网络
Why does this code give me an answer of 25? public int findGcd() { int num = this.num; int den = this.den;

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 g开发者_如何学Coes or run?


Because gcd(25, 100) = 25 probably


It is called the Euclidean Algorithm.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号