当前位置:网站首页>求最大公约数与最小公倍数(C语言)
求最大公约数与最小公倍数(C语言)
2022-07-07 08:12:00 【璞玉牧之】
一、题目
写两个函数,分别求两个整数的最大公约数和最小公倍数,用主函数调用这两个函数。两个整数由键盘输入。
二、分析及代码
1.思路
- 最大公约数:两个或多个整数共有约数中最大的一个。利用辗转相除法计算。
- 最小公倍数:两个或多个整数共有倍数中除0外最小的一个。由于两个数的乘积等于这两个数的最大公约数与最小公倍数的积,所以,两个数的最小公倍数等于这两个数的乘积除最大公约数。
- 分析思路:分别定义两个函数,和两个变量a,b。第一个函数用辗转相除法求a,b的最大公约数,假设a>b,令a/b得到余数r,再将b作为被除数,r作为除数,得到余数…直至余数为0。第二个函数利用上述公式可求得两个数的最小公倍数。
2.代码
代码如下:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int Greatest_Common_Divisor(int a,int b); //函数声明
int Least_Common_Multiple(int a,int b,int m); //函数声明
int a,b,m,x;
scanf("%d,%d",&a,&b);
m=Greatest_Common_Divisor(a,b);
x=Least_Common_Multiple(a,b,m);
printf("%d和%d的最大公约数是:%d\n",a,b,m);
printf("%d和%d的最小公倍数是:%d\n",a,b,x);
return 0;
}
int Greatest_Common_Divisor(int a,int b) //求最大公约数
{
int temp,r;
if(b>a) //让两个数中较大的数作为被除数
{
temp=a;
a=b;
b=temp;
}
while((r=a%b)!=0)
{
a=b; //使除数b变为被除数a
b=r; //使余数r变为除数b
}
return b;
}
int Least_Common_Multiple(int a,int b,int m) //求最小公倍数
{
return (a*b/m);
}
3.运行结果

边栏推荐
- Pdf document signature Guide
- ORM -- grouping query, aggregation query, query set queryset object properties
- Download Text, pictures and ab packages used by unitywebrequest Foundation
- The new activity of "the arrival of twelve constellations and goddesses" was launched
- Using keras in tensorflow to build convolutional neural network
- Postman interface test II
- 【acwing】789. Range of numbers (binary basis)
- STM32基础知识—内存映射
- Wallys/IPQ6010 (IPQ6018 FAMILY) EMBEDDED BOARD WITH ON-BOARD WIFI DUAL BAND DUAL CONCURRENT
- A wave of open source notebooks is coming
猜你喜欢

搭建物联网硬件通信技术几种方案

Remote meter reading, switching on and off operation command

XML configuration file parsing and modeling

柏拉图和他的三个弟子的故事:如何寻找幸福?如何寻找理想伴侣?

虚数j的物理意义

01 use function to approximate cosine function (15 points)

Enterprise practice | construction of banking operation and maintenance index system under complex business relations

【acwing】786. Number k

VS Code指定扩展安装位置

STM32 ADC和DMA
随机推荐
【acwing】786. 第k个数
IO模型复习
The Hal library is configured with a general timer Tim to trigger ADC sampling, and then DMA is moved to the memory space.
The new activity of "the arrival of twelve constellations and goddesses" was launched
ES6中的原型对象
[higherhrnet] higherhrnet detailed heat map regression code of higherhrnet
UnityWebRequest基础使用之下载文本、图片、AB包
request对象对请求体,请求头参数的解析
Bit operation ==c language 2
A wave of open source notebooks is coming
China's first electronic audio category "Yamano electronic audio" digital collection is on sale!
STM32 Basics - memory mapping
Win10 installation vs2015
Guid primary key
The story of Plato and his three disciples: how to find happiness? How to find the ideal partner?
Guide de signature du Code Appx
fiddler-AutoResponder
【acwing】789. 数的范围(二分基础)
学习记录——高精度加法和乘法
IPv4套接字地址结构