6.最大公因数和排序

#include "stdio.h"
#include "stdlib.h"
#include "time.h"
long long count = 0;
int gcd1(int n, int m) {
    int i, factor = 1;
    count = 0;
    for (i = 2; i <= n && i <= m; i++) {
        while (m % i == 0 && n % i == 0) {
            factor *= i;
            m /= i;
            n /= i;
            count++;
        }
    }
    printf("执行次数为:%lld ", count);
    return factor;
}
// 辗转相除
int gcd2(int n, int m) {
    int t = m % n;
    count = 0;
    while (t) {
        m = n;
        n = t;
        t = m % n;
        count++;
    }
    printf("执行次数为:%lld ", count);
    return n;
}
// 更相减损术
int gcd3(int n, int m) {
    count = 0;
    while (n != m) {
        if (n > m)
            n -= m;
        else
            m -= n;
        count++;
    }
    printf("执行次数为:%lld ", count);
    return n;
}

// 冒泡排序
void sort1(int a[], int n) {
    clock_t start, end;
    start = clock();
    int i, j;
    count = 0;
    for (i = 0; i < n; i++) {
        for (j = 0; j < n - i; j++) {
            if (a[j] > a[j + 1]) {
                int t = a[j];
                a[j] = a[j + 1];
                a[j + 1] = t;
                count++;
            }
        }
    }

    end = clock();
    for (i = 0; i < n; i++) {
        printf("%d ", a[i]);
    }
    printf("\n计时法:%.5lf秒\n", (double)(end - start) / CLK_TCK);
    printf("计数法:%lld 次", count);
}

void sort2(int a[], int n) {
    clock_t start, end;
    start = clock();
    count = 0;
    int bound, exchange = n - 1, j;
    while (exchange != 0) {
        bound = exchange;
        exchange = 0;
        for (j = 0; j < bound; j++) {
            if (a[j] > a[j + 1]) {
                int temp = a[j];
                a[j] = a[j + 1];
                a[j + 1] = temp;
                exchange = j;
                count++;
            }
        }
    }
    end = clock();
    for (j = 0; j < n; j++) {
        printf("%d ", a[j]);
    }
    printf("\n计时法:%.5lf秒\n", (double)(end - start) / CLK_TCK);
    printf("计数法:%lld 次\n", count);
}

int main() {
    int n, m;
    puts("请输入两个数以求其最大公因数:");
    scanf("%d%d", &n, &m);
    printf("算法1求出最大公因数为:%d\n", gcd1(n, m), count);
    printf("算法2求出最大公因数为:%d\n", gcd2(n, m), count);
    printf("算法3求出最大公因数为:%d\n", gcd3(n, m), count);
    int x;
    int a[100010] = {0}, j = 0;
    srand((unsigned int)time(NULL));
    int i = 0;
    for (i = 0; i < 100000; i++) {
        x = rand() % 500000;
        a[j++] = x;
    }
    puts("算法1排序中....");
    sort1(a, 100000);
    for (i = 0; i < 100000; i++) {
        x = rand() % 500000;
        a[j++] = x;
    }
    puts("算法2排序中....");
    sort2(a, 100000);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值