【图解算法使用C++】1.2 生活中的算法

图解算法使用C++

一、计算思维与程序设计

1.2 生活中到处都是算法

  • 计算最大公约数(辗转相除法)算法简介
// C++
#include<iostream>
#include<stdio.h>
using namespace std;

int test_way1(int Num1,int Num2){
    int tmp;
    if(Num1<Num2){
        tmp = Num1;
        Num1 = Num2;
        Num2 = tmp;
    }
    while(Num2 !=0){
        tmp = Num1 % Num2;
        Num1 = Num2;
        Num2 = tmp;
    }
    return Num1;
}

int test_way2(int Num1,int Num2){
    if(Num1 % Num2==0) return Num2;
    else return test_way2(Num2,Num1 %Num2);
}

int main(){
    int Num1 = 10;
    int Num2 = 20;
    printf("Num1:%d ,Num2:%d \n",Num1,Num2);
    int res = test_way1(Num1,Num2); 
    // int res = test_way2(Num1,Num2); 
    cout << "最大公约数为:" << res << endl;
    return 0;
}

附上使用Python递归解法:

def gcd(a,b):
    while b!=0:
        b,a = a%b,b
    return a

print(gcd(10,20))
posted @ 2022-04-28 09:31  野哥李  阅读(13)  评论(0编辑  收藏  举报  来源