Algorithm: Euclid's Algorithm

本文介绍了一种使用欧几里得算法求两个正整数最大公约数的方法。该算法通过不断取余数并交换数值的方式,直至余数为零,此时的除数即为两数的最大公约数。文章提供了详细的算法步骤及Java实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Algorithm E

Algorithm E (Euclid’s algorithm). Given two positive integers m and n, find
their greatest common divisor, that is, the largest positive integer that evenly
divides both m and n.
E1. [Find remainder.] Divide m by n and let r be the remainder. (We will have
0<= r < n.)
E2. [Is it zero?] If r = 0, the algorithm terminates; n is the answer.
E3. [Reduce.] Set m <– n, n <– r, and go back to step E1. |


Flow diagram

这里写图片描述


Java program

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Created with IntelliJ IDEA.
 * User: 1O1O
 * Date: 12/15/13
 * Time: 6:52 PM
 * :)~
 * Euclid's Algorithm:ALGORITHMS
 */
public class Main {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Please input a positive integer for m:");
        int m = Integer.parseInt(br.readLine());

        System.out.print("Please input a positive integer for n:");
        int n = Integer.parseInt(br.readLine());

        int r;

        do{
            r = m%n;
            if(r == 0){
                System.out.println("The greatest common divisor of m and n is:"+n);
                break;
            }else {
                m = n;
                n = r;
            }
        }while (true);
    }
}

Inputs & Outputs

Please input a positive integer for m:12
Please input a positive integer for n:45
The greatest common divisor of m and n is:3

Reference

<< The Art of Computer Programming: Fundamental Algorithms>> VOLUME 1, DONALD E. KNUTH

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值