MSVC的gcd
  • 板块灌水区
  • 楼主BD_AZZR_CN
  • 当前回复0
  • 已保存回复0
  • 发布时间2024/8/7 10:43
  • 上次更新2024/8/7 11:33:20
查看原帖
MSVC的gcd
767779
BD_AZZR_CN楼主2024/8/7 10:43

测试代码

#include <time.h>
#include <iostream>
#include <numeric>
using namespace std;
#define N 10000




int __builtin_ctzll(int x) {
    int count = 0;
    while (x != 0) {
        x &= (x - 1);  // 清除最右边的1
        count++;
    }
    return count;
}
[[nodiscard]] unsigned long long _gcd(unsigned long long _Mx, unsigned long long _Nx) noexcept /* strengthened */ {

    if (_Mx == 0U) {
        return static_cast<unsigned long long>(_Nx);
    }
    if (_Nx == 0U) {
        return static_cast<unsigned long long>(_Mx);
    }
    const unsigned long _Mx_trailing_zeroes = static_cast<unsigned long>(__builtin_ctzll(_Mx));
    unsigned long _Nx_trailing_zeroes = static_cast<unsigned long>(__builtin_ctzll(_Nx));
    const unsigned long _Common_factors_of_2 = (::std::min)(_Mx_trailing_zeroes, _Nx_trailing_zeroes);
    _Mx >>= _Mx_trailing_zeroes;
    for (;;) {
        _Nx >>= _Nx_trailing_zeroes;
        if (_Mx > _Nx) {
            unsigned long long _Temp = _Mx;
            _Mx = _Nx;
            _Nx = _Temp;
        }
        _Nx -= _Mx;
        if (_Nx == 0U) {
            return static_cast<unsigned long long>(_Mx << _Common_factors_of_2);
        }
        _Nx_trailing_zeroes = static_cast<unsigned long>(__builtin_ctzll(_Nx));
    }
}







template<typename _EuclideanRingElement>
_EuclideanRingElement
__gcd(_EuclideanRingElement __m, _EuclideanRingElement __n)
{
    while (__n != 0)
    {
        _EuclideanRingElement __t = __m % __n;
        __m = __n;
        __n = __t;
    }
    return __m;
}

clock_t start, end;
static double test(int a,int b) {
    clock_t start, end;
    start = clock();
    __gcd(a, b);
    end = clock();
    return ((double)(end - start) / CLOCKS_PER_SEC);
};
static double test2(int a, int b) {
    clock_t start, end;
    start = clock();
    _gcd(a, b);
    end = clock();
    return ((double)(end - start) / CLOCKS_PER_SEC);
};
static double test3(int a, int b) {
    clock_t start, end;
    start = clock();
    gcd(a, b);
    end = clock();
    return ((double)(end - start) / CLOCKS_PER_SEC);
};
int main()
{
    double time_1 = 0;
    double time_2 = 0;
    double time_3 = 0;
    srand(time(0));
    int t1, t2;
    for (int i = 1; i <= 10000000; i++) {
        t1 = ((unsigned long long)rand());
        t2 = ((unsigned long long)rand());
        time_1 += test(t1,t2);
        time_2 += test2(t1, t2);
        time_3 += test3(t1,t2);
    }
    printf("GCC:%lf\nMSVC':%lf\nMSVC:%lf\n", time_1, time_2,time_3);
    system("pause");
    return 0;
}

gcc::__gcd

MSVC::gcd爆改

MSVC::gcd原版

设备信息:VS2022 crpDebug x64

本来想写个快板子的

2024/8/7 10:43
加载中...