gpt4 book ai didi

c++ - 扩展 GCD 算法

转载 作者:行者123 更新时间:2023-11-28 03:44:57 25 4
gpt4 key购买 nike

我已经为扩展 GCD 算法编写了以下算法,只是不知道如何返回三元组,有人可以帮助我吗?

#include<iostream>
#include<math.h>
using namespace std;
int gcd(int a,int b) { return (b==0 ?a:gcd(b,a%b));}
long long gcd(long a,long b) { return (b==0 ?a:gcd(b,a%b));}
template<class Int> Int gcd(Int a,Int b) { return (b==0 ?a:gcd(b,a%b));}
template<class Int>
struct Triple
{
Int d,x,y;
Triple(Int q,Int w,Int e) :d(q),x(w),y(e)) {}

};

//extended GCD
/* computes d=gcd(a,b)
also x and y such that d=a*x+y*b and return tripls (d,x,y)
*/
template<class Int>
Triple <Int> egcd(Int a,Int b) {

if(!b) return Triple<Int>(a,Int(1),Int(0));
Triple<int>q=egcd(b,a%b);
return Triple<Int>(q.d,q.y,q.x-a/b*q.y);
}

int main(){

int a=35;
int b=13;




return 0;
}

如何使用我的三重结构构造函数完成它?请帮助我

最佳答案

(1) 修正构造函数,编译不通过(去掉一个括号):

Triple(Int q,Int w,Int e) : d(q), x(w), y(e) {}

(2) 在 main() 中调用:

Triple <int> t = egcd(a, b);
cout << t.d << ", " << t.x << ", " << t.y << endl;

关于c++ - 扩展 GCD 算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7943888/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com