• 求最大公因数的三种算法


    欧几里得算法

    #include<iostream>
    using namespace std;

    int fun(int a, int b){
    if (a >= b){
    int r = a%b;
    if (r == 0)
    return b;
    else
    fun(b, r);
    }
    else
    fun(b, a);
    }

    int main()
    {
    int a, b;
    cout << "请输入两个整数" << endl;
    cin >> a>>b;
    int r = 1;
    r = fun(a, b);
    cout << a << "和" << b << "的最大公约数是:" << r << endl;
    }在这里插入代码片
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    连续整数检测法

    #include<iostream>
    using namespace std;

    int fun2(int a, int b){
    int c;
    if (a <= b)
    c = a;
    else
    c = b;
    for (c; c >= 1; c--)
    {
    if (a%c== 0 && b%c== 0)
    break;
    }
    return c;

    }
    int main()
    {
    int a, b;
    cout << "请输入两个整数" << endl;
    cin >> a>>b;
    int r = 1;
    r = fun2(a, b);
    cout << a << "和" << b << "的最大公约数是:" << r << endl;
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    分解公共质因数法

    #include<iostream>
    #include<string>
    #define len 100
    using namespace std;

    //找一个数的质因子
    void fun1(int a,int* s) {
    bool flag = true;
    int count = -1;
    for (int i = 1; i < a; i++) {
    if (a%i == 0) //一个因子 接下来判断是否是素数,如果是素数flag=1 则将其加入数组,如果不是i++
    {
    for (int j = 2; j <= i - 1; j++) {
    if (j%i == 0)
    flag = false;
    }
    if (flag) {
    count++;
    *(s+count)=i;
    }
    }
    }
    }

    //遍历两个数的质因子数组,如果相同则累乘
    int fun2(int *s1, int *s2,int len1,int len2) {
    int mul = 1;
    for (int i = 1; i < len1; i++)
    {
    if (*(s1 + i) != 0) { //数组遇到0就停止,非0再比较,0代表没有因子
    for (int j = 1; j < len2; j++)
    {
    if (*(s2 + j) == 0) //说明数组s2中没有因子了,退出本层循环
    break;
    else if (*(s1 + i) == *(s2 + j)) //说明当前遍历的S1数组中的值是两个数组的公因子,累乘后退出本层循环
    {
    mul = mul * (*(s1 + i));
    break;
    }
    else //非公因子,进入下一次循环
    continue;
    }
    }
    else
    break;
    }
    return mul;
    }


    int main()
    {
    int a, b,r;
    cout << "请输入两个整数" << endl;
    cin >> a >> b;
    int s1[len] = {0};
    int s2[len] = {0};
    fun1(a,s1);
    fun1(b, s2);
    r = fun2(s1, s2,len,len);
    cout << a << "和" << b << "的最大公约数是:" << r << endl;
    system("pause");
    }

    ---------------------

  • 相关阅读:
    java实现调用打印机代码
    java合并PDF文件
    关于如何把项目做得更好的一次思考
    web语义化之SEO和ARIA
    快速理解web语义化
    使用HTML5地理位置定位到城市的方法及注意事项
    Plupload上传插件简单整理
    两列布局——左侧宽度固定,右侧宽度自适应的两种方法
    Java并发编程之线程基础
    Spring Boot学习之YAML文件配置
  • 原文地址:https://www.cnblogs.com/hyhy904/p/11198592.html
Copyright © 2020-2023  润新知