python递归以及c语言递归实现求最大公约数(补充上文)

HRBU-ACM 数论2-最大公约数(欧几里得) 高中我们都学过辗转相除法,如果有人没学过或者忘记了那也没关系,在这里我们在讲解一遍欧几里得算法(求最大公约数)   欧几里德算法是用来求两个正整数最大公约数的算法。是由古希腊数学家欧几里德在其著作《The Elements》中最早描述了这种算法,所以被命名为欧几里德算法。 扩展欧几里德算法可用于RSA加密等领域。 假如需要求 1997 和 615 两个正整数的最大公约数,用欧几里德算法,是... 阅读详情

前面已经写过了欧几里得算法(即辗转相除法)c语言的写法,今天用python和c的递归来实现辗转相除法

需注意:python代码中当输入999和991时,会造成互质现象

##输入M和N
M = int(input())
N = int(input())
M1 = M
N1 = N
if M < N:
    M , N = N , M  //比较M N大小并进行交换
R = M % N
while R != 0:
    M = N
    N = R
    R = M % N
if N !=1:
    print('%d和%d的最大公约数为%d。' %(M1,N1,N))
else:
    print('%d与%d互质。' %(M1,N1))

c语言中是如和实现的呢:

#include <stdio.h>
void Swap(int x, int y)
{
	int z = 0;
	z = x;
	x = y; 
	y = z;
}
int gcd(int x,int y)
{
	if(y>x)
	{
		Swap(x,y);
	}
	if(x % y == 0)
	{
		return y;
	}
	else
		return gcd(y,x%y);	
}
int main()
{
	int m ,n;
	scanf("%d %d",&m,&n);
	printf("最大公约数为%d",gcd(m,n));
	return 0;
}

由于c语言和python语言的区别,不能直接进行数值交换,因此在此处又重新定义了判断大小并交换的函数---

本周python递归其他题目:
利用递归实现斐波那契数列的计算:

 Fibonacci数列的递归算法 输入:正整数n 输出:Fibonacci数列的第n项 Fib(n)
1 IF n≤2 2 THEN RETURN 1
3 RETURN Fib(n-1) + Fib(n-2) //self call

def fab(n):
    if n <= 2:
        return 1
    else:
        return fab(n-1) + fab(n-2)
             
    
if(__name__=="__main__"):
    global result
    n_str = input('请输入需要计算fabonacci数列的第几个元素:')
    n = int(n_str)
    result=fab(n)
    print(result)

汉诺塔游戏:
此代码可实现每一步的操作过程以及操作总次数:
 

def Hanoi(n, A, C, B):
    global count
    if n <1:
        print('invalid input')
    elif n == 1:
        print("%d:\t%s ---> %s" %(count,A,C))
        count = count +1
    else:
        Hanoi(n-1,A,B,C)
        Hanoi(1,A,C,B)
        Hanoi(n - 1,B,C,A)
    
if(__name__ == "__main__"):
    count = 1
    n = int(input('请输入A柱子上的圆盘个数:'))
    Hanoi(n,'A','C','B')

有问题请指教!

Python实战:用欧几里得算法求最大公约数的5种写法(附性能对比) 本文详细介绍了Python中实现欧几里得算法求最大公约数的五种方法,包括经典递归、尾递归优化、迭代解法、内置math库方案及Numba加速版本,并附有性能对比分析。通过实际测试数据,帮助开发者选择最适合其应用场景的GCD计算方案,提升算法效率与代码质量。 阅读详情

相关推荐

Python:实现辗转相除法算法(附完整源码)

Python:实现辗转相除法算法(附完整源码)

希望我的博客,能帮上你解决学习中工作中所遇到的问题 2025

Python辗转相除法

使用欧几里得算法(辗转相除法),编写递归函数,求两个数的最大公约数。

m0_61717621的博客 1540

Python基于递归和非递归算法求两个数最大公约数、最小公倍数示例

主要介绍了Python基于递归和非递归算法求两个数最大公约数、最小公倍数,涉及Python递归算法、流程循环控制进行数值运算相关操作技巧,需要的朋友可以参考下

python用递归方式实现最大公约数_Python实现求两数最大公约数(四种方法)

1. 辗转相除法(while循环实现)(1) 两数求余temp = p % q(2) temp = 0时,q为最大公约数(3) temp !=0时,p = q;q = temp注:该循环的是否继续的判断条件就是temp是否为0def fuc(p, q):temp = p % qwhile temp!=0:p = qtemp = pq = temp % qreturn q12345672.辗转相减法...

weixin_39788703的博客 5565

Python基于递归算法求最小公倍数和最大公约数示例

本文实例讲述了Python基于递归算法求最小公倍数和最大公约数。分享给大家供大家参考,具体如下: # 最小公倍数 def lcm(a, b, c=1): if a * c % b != 0: return lcm(a, b, c+1) else: return a*c test_cases = [(4, 8), (35, 42), (5, 7), (20, 10)] for case in test_cases: print('lcm of {} & {} is {}'.format(*case, lcm(*case))) def lcm(a, b): for

python如何求解两数的最大公约数

主要为大家详细介绍了python如何求解两数的最大公约数,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

python辗转相除法算法_辗转相除法的算法

展开全部自然语言描述用辗转相除法确定两个正整数e69da5e6ba903231313335323631343130323136353331333339666665 a 和 b(a≥b) 的最大公因数gcd(a,b):当a mod b=0 时gcd(a,b)=b,否则gcd(a,b) = gcd(b,a mod b)递归或循环运算得出结果伪代码这个算法可以用递归写成如下:function gcd(a...

weixin_39907850的博客 2332

LSTM模型股价波动率预测(含Python代码)

源代码文件可在gzh’finance褪黑素'回复【24012203】获取。

celiaweiwei的博客 3774

【一本通】用递归方法求两个数m和n的最大公约数

用递归方法求两个数m和n的最大公约数。

✨ 欢迎来到【Seal ^_^ 的优快云博客】!✨ 4755

VisionMaster图像源模块的5个隐藏功能:从自动切换到二次开发接口

本文深入解析了VisionMaster图像源模块的5个隐藏功能,从基础的自动切换与字符触发过滤,到高级的脚本扩展与基于COM组件的二次开发接口。这些功能能显著提升工业视觉项目的自动化水平、灵活性与系统集成能力,帮助开发者实现更高效的离线测试流水线和外部精确控制。

rgv23456789的博客 651

matplotlib三维画图之观察博弈论混合策略下纳什均衡点

参考链接: 博弈论入门20讲之第16讲-猜谜游戏-散户如何赢庄家 游戏背景: 我的期望是: 你的期望是: 使用Python的matplotlib画图: import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = Axes3D(fig) X = np.linspace(0, 1, 100) Y = np.linspace(0, 1,

敲代码的小风 1257

Java实现求n个数的最大公约数和最小公倍数

一、题目要求 求N个数的最大公约数和最小公倍数。用C或C++或java或python语言实现程序解决问题。 1.程序风格良好(使用自定义注释模板) 2.提供友好的输入输出,并进行输入数据的正确性验证。 二、算法分析 注:遵循一条数学定理:两数之积等于两数的最大公约数与最小公倍数之积 n个数的最大公约数和最小公倍数的求法是基于两个数的求法之上的: 1、先求两个数的最大公约数和最小公倍数 2、再用所求...

包包的博客 6051

全网最新首发纯干货:微信数据库表结构完整分析(一)

找不到微信DB表结构说明?找不到具体字段的解释?来这里,全网最完整版!!!

killghosts的博客 4924

求N个数的最大公约数和最小公倍数以及Hankson"逆问题"(python)

求N个数的最大公约数和最小公倍数以及Hankson"逆问题"(python) 一、题目要求 1.基本要求: 求N个数的最大公约数和最小公倍数。用C或C++或java或python语言实现程序解决问题 2.提高要求: 已知正整数a0,a1,b0,b1,设某未知正整数x满足: (1)x和a0的最大公约数是a1; (2)x和b0的最小公倍数是b1。 输入数据保证a0能被a1整除,b1能被b0整除。 对于...

Elf.筱焱的博客 1万+

【移远EG800K-CN】从AT指令到MQTT实战:4G模块云端通信全解析

本文详细解析移远EG800K-CN 4G模块的AT指令应用与MQTT云端通信实战。从硬件连接到网络配置,再到MQTT协议的数据上报与命令接收,提供了完整的物联网通信解决方案,帮助开发者快速实现设备与云端的稳定数据交互。

o1p2q3r的博客 559

Windows 11 安装 MySQL 8.4:安装包方式、下载、安装、使用

本文详细介绍了在 Windows 11 系统下通过 MSI 安装包方式安装 MySQL 8.4 LTS 社区版的完整流程,包括版本选择、下载、自定义安装路径、服务配置、日志设置、示例数据库创建及后续使用方法。同时提供了命令行客户端与图形化工具 DBeaver 的连接与操作演示,适合初学者和开发者快速搭建本地 MySQL 开发环境。

寒水馨 · 轻量级技术文档 · hanshuixin.org 2255

欧几里得算法求最大公约数python,算法:欧几里得求最大公约数(python版)

#欧几里得求最大公约数#!/usr/bin/env python#coding -*- utf:8 -*-#iterationdef gcd(a,b):if b==0:return aelse:return gcd(b, remainder(a, b))#此方法仅仅书用于a和b都为正数def gcd_1(a,b):while(b>0):rem = remainder(a,b)a = bb =...

weixin_34731217的博客 2545

医学图像的对抗攻击:模型安全性与鲁棒性分析

医学图像的对抗攻击:模型安全性与鲁棒性分析 ,人工智能,计算机视觉,大模型,AI,本文围绕医学图像的对抗攻击展开,分析了其对AI模型的威胁。介绍了对抗样本定义、攻击原理,以及FGSM、BIM、PGD等常见攻击方法,还给出了相关代码示例。阐述了攻击对模型诊断准确性和可信度的影响,提出对抗训练、输入预处理、模型集成等提升模型安全性与鲁棒性的方法,探讨了评估指标、数据集和流程,分析了实际应用中的挑战与应对策略,最后展望了未来发展趋势。

不踩坑,不知道坑有多深;不总结,踩过的坑白踩。 18万+

3288:【例47.3】 最大公约数(C、C++、python)

3288:【例47.3】 最大公约数(C、C++、python)

青少年趣味编程 1735

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

用递归求最大公约数

#include int GCD_C(int a,int b){ if(a % b != 0){ int z; z = a; a = b; b = (z % b); return GCD_C(a,b); } else { printf("辗转相除法求最大公约数:%d\n",b); return; } } int GCD_J(int x,int y){ if

Pro_阳 1083

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

求两个数的最大公约数(C ,Python,java实现)

#include  int max(int p_a,int p_b) { if(p_b==0) return p_a; else return max(p_b,p_a%p_b); } void main() { int a,b; printf("Input two numbers:\n"); scanf("%d %d",&a,&b); if(b printf("最大公约

2066

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

N个数求最大公约数和最小公倍数

第二章:程序的算法设计 1.实验目的 a.明确算法的概念和特点。 b.通过对问题的分析,设计合理的算法解决问题; c.在原有算法的基础上做更进一步的改进 2.题目描述 求n个数的最大公约数和最小公倍数,用C或C++或java或python语言实现程序解决问题。 1.程序风格良好(使用自定义注释模板) 2.提供友好的输入输出,并进行输入数据的正确性验证。 3.需求分析 通过...

qq_42272391的博客 1006

求n个数的最大公约数和最小公倍数

第2章 一.基本要求: 求N个数的最大公约数和最小公倍数。用C或C++或java或python语言实现程序解决问题。 1.程序风格良好(使用自定义注释模板) 2.提供友好的输入输出,并进行输入数据的正确性验证。 二. 1.题目分析 求n个数的最大公约数和最小公倍数,求两个数的最大公约数的基础上加以补充修改使用辗转相除法求得。 2.算法构造...

qq_42728144的博客 1068

最大公约数gcd,最小公倍数lcm--C、Java、Python

计算最大公约数gcd,最小公倍数lcm–C、Java、Python C语言: #include<stdio.h> // 最大公约数方法 int gcd(int a, int b) { return (a % b == 0) ? b : gcd(b, a%b); } // 最小公倍数 int lcm(int a, int b) { return a*b/gcd(a, b); } int main() { int number1 = 6, number2 = 8; printf

qq_45772965的博客 427

(c语言)1、最大公约数和最小公倍数

1、首先先了解分解质因数:每个合数都可以写成几个质数相乘的形式。 如30=2×3×5 。 2、最大公约数:指两个或多个整数共有约数中最大的一个。 一般用gcd(a,b)来表示a和b的最大公约数,则有结论 gcd(a,b)=gcd(b,a%b). 证明: 设a=kb+r; d为a,b的公约数 则有r=a%b.(a和b为正整数) 因为r=a-kb;d又为a,b的公约数 ; 所以r/d=a/d-kb/d;显然r/d是整数 所以d也是b和r的公约数 由于d的任意性,a和b的公约数都是b和a%b的公约数 所以两者最大

qq_35841609的博客 1091
上一篇: 21年11月19日周结 c语言和python
下一篇: 函数调用及其链式访问
ZZRBlogger
博客等级 码龄5年 10粉丝 8原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值