目录
一、❀分别用辗转相除法和定义法编码实现求两数a,b最大公约数,并比较两种算法运行时间的差异。
一、❀分别用辗转相除法和定义法编码实现求两数a,b最大公约数,并比较两种算法运行时间的差异。
1、设计思路和关键点
辗转相除法: ①手动输入两个正整数。 ②设置程序开始的时间点,并记录。 ③判断a,b大小,将a做为大的被除数。 ④用a%b求出余数,再让a=b,让余数等于b。直到b=0结束。 ⑤设置程序结束的时间点,并记录。 ⑥输出最大公约数,并且用程序的结束时间和程序的开始时间计算程序的运行时间。⑦ 定义法: ①手动输入两个正整数。 ②设置程序开始的时间点,并记录。 ③判断a,b大小,将a做为大的数。 ④利用循环,同时用同一个逐渐递增减变量i = a,来对a和b进行余数操作,直到a,b 两个数同时为0,停止程序。 ⑤设置程序结束的时间点,并记录。 ⑥输出最大公约数,并且用程序的结束时间和程序的开始时间计算程序的运行时间。
2、伪代码
辗转相除法: Begin(算法开始) 输入a,b 记录程序开始时间 IF b>a then do a 和b互换值 While b=0 then do a%b求出来最大公约是 记录程序结束时间 Pintf 最大公约数 Pintf 记录程序运行时间 End(算法结束) 定义法: Begin(算法开始) 输入a,b 记录程序开始时间 IF b>a then do a和b互换值 For i=a then do If a%i==0 && b%i==0 then do 记录程序结束时间 Printf最大公约数 Printf 记录程序运行时间 End(算法结束)
3、代码
#include<stdio.h> #include <stdlib.h> #include <time.h> int toss(int a,int b){ int t,p; clock_t start_time; clock_t finish_time; float program_time; start_time=clock(); if(b>a){ t = a; a = b; b = t; } while(b!=0){ p = a%b; a = b; b = p; } printf("最大公约数为%d\n",a); finish_time=clock(); program_time=(float)(finish_time-start_time)/CLOCKS_PER_SEC; printf("Program complete time: %f\n",program_time); } int define(int a,int b){ clock_t start_time; clock_t finish_time; float program_time; start_time=clock(); int t; if(b>a){ t = a; a = b; b = t; } for(int i = a;i>=1;i--){ if(a%i==0 && b%i==0){ printf("最大公约数为%d\n",i); finish_time=clock(); program_time=(float)(finish_time-start_time)/CLOCKS_PER_SEC; printf("Program complete time: %f\n",program_time); return 1; } } } int main(){ int a,b; printf("please input a:"); scanf("%d",&a); printf("please input b:"); scanf("%d",&b); //辗转相除法 toss(a,b); //定义法 define(a,b); return 0; }
4、结果
二、❀分数分解算法
分数分解算法:把真分数a/b分解为若干个分母为整数,分子为1的埃及分数
#step1:寻找并输出小于a/b的最大埃及分数1/c
#step2:若c>900000000,则退出
#step3:11
#step4:否则,继续1,2,3步骤
1、设计思路和关键点
①手动输入两个正整数。 ②求出阿a,b的最大埃及数。 ③判断最大埃及数的分母是否大于900000000。 ④若大于则结束程序。 ⑤若c<=900000000,求差:a/b-1/c,并把差整理为最简真分数a/b;若a/b为埃及分数, 则输出后结束。
2、伪代码
Begin(算法开始) 输入a,b While 1 then do c = b/a+1 IF c>900000000 then do 结束程序 Else then do n = a*c - b; //分子 m = b*c; //分母 While b!=0 then do p = a%b; a = b; b = p; End 求出来最大公约数 Printf a/b End(算法结束)
3、代码
#include<stdio.h> int egypt(int a,int b){ int c = b/a+1; printf("1/%d",c); printf("\n"); return c; } int toss(int a,int b){ int p; while(b!=0){ p = a%b; a = b; b = p; } return a; } int score(int a,int b){ int m,n,t,c; while(1){ c = egypt(a,b); if(c>900000000){ return 1; } else{ n = a*c - b; //分子 m = b*c; //分母 t = toss(n,m);//求出来最大公约数 a = n/t; b = m/t; if(a == 1){ printf("%d/%d",a,b); return 1; } } } } int main(){ int a,b,c,r; printf("please input a:"); scanf("%d",&a); printf("please input b(a<b):"); scanf("%d",&b); score(a,b); }
4、结果