C language practice question 16

foreword

Why today is May 4th! ! ! !

Question sixteen

Question:
Input two positive integers m and n, find their greatest common divisor and least common multiple.

Sui Sui Nian:
Ever since I recalled functions, I feel that functions can be used in everything, and it is easy to use functions in this question.

My idea:
2. Input: positive integer m, n
Output: the greatest common divisor and the smallest multiple of these numbers.
3. Analysis:
The least common multiple = the product of the two input numbers divided by their greatest common divisor. The key is to find the greatest common divisor. To find the greatest common divisor,
use the rolling and dividing method (also known as the Euclidean algorithm, I read it in the book) of)

The first step: a / b, let r be the remainder (0≤r)
The second step: swap: set a←b, b←r, and return to the first step.

My process:
method one:

#include<stdio.h>
int main()
{
    
    
    int a,b,t,r,n;
    printf("请输入两个数字:\n");
    scanf("%d %d",&a,&b);
    if(a<b)
    {
    
    t=b;b=a;a=t;}
    r=a%b;
    n=a*b;
    while(r!=0)
    {
    
    
        a=b;
        b=r;
        r=a%b;
    }
    printf("这两个数的最大公约数是%d,最小公倍数是%d\n",b,n/b);
    
    return 0;
}

Method 2: use function

#include<stdio.h>
void f14(int m,int n){
    
    
    int i=0;
    int num=1;
    int temp1=m,temp2=n;//用两个变量寄存m,n的值
    int min=m<n?m:n;//求得m,n中的较小值

    for(i=2;i<=min;i++){
    
    
        if((m%i==0)&&(n%i==0)){
    
    
            //printf("%d\n",i);
            num*=i;
            m=m/i;
            n=n/i;
            min=min/i;
            i=1;//i的还原,不然在执行一次循环体后,i++=3,下次循环时,会将i=2这个商给跳过,出现问题
            //printf("%d\n",min);
        }
    }
    printf("最大公约数为:%d\n",num);
    printf("最小公倍数为:%d\n",temp1*temp2/num);
}
int main(){
    
    
        printf("请输入两个数:");
    int m,n;
    scanf(" %d %d",&m,&n);
    f14(m,n);
        return 0;
}

Method 3: Rolling and dividing method (I understand)

#include<stdio.h>
#include<math.h>

int main()
{
    
    
    int a,b,n,t,j;
    printf("输入2个正整数:");
    scanf("%d%d",&a,&b);
    if(a<b)
    {
    
    
        t=a;
        a=b;
        b=t;
    }
    n=a%b;
    j=a*b;
    while(n!=0)
    {
    
    
        a=b;
        b=n;
        n=a%b;
    }
    printf("%d是最大公约数\n",b);
    printf("%d是最小公倍数\n",j/b);
}

Running results:
insert image description here
Summary
I feel that I am getting more and more used. The method can also write the second from the first one.

Guess you like

Origin blog.csdn.net/weixin_52248428/article/details/116457347