Find the greatest common divisor The greatest common factor language realizes the output of the greatest common divisor (factor) of an integer, and four algorithms are implemented

algorithm design:

method one:

          The first way of thinking is enumeration (exhaustive method, enumeration method) , but enumeration can be divided into two methods. The first one uses the exhaustive method to list all the common divisors that meet the conditions in order from small to large (the initial value is 1, and the maximum value is the smaller number among the two integers), and outputs the largest one; the second According to the order from large (the smaller number of two integers) to small (to the smallest integer 1), find the first natural number that can divide two integers at the same time, which is what you want.

         The code example is as follows:

#include <stdio.h>

int main()
{
    int a, b;
    scanf("%d %d", &a, &b);//低版本编译器使用scanf 高版本编译器使用scanf_s
    int i;
    int gcd;
    gcd = 1;
    
    for(i = (a<b?a: b); i > 0; i--)
    {
        if(a % i == 0 && b % i == 0)
        {
            gcd = i;
            break;
        }
    }
    printf("gcd = %d\n", gcd);
    
    return 0;
}
#include <stdio.h>
int Get_Max_Comm_Divisor(int num1, int num2)
{
    int i = 0;
    //获取两个整数的最小值
    int min = num1 < num2 ? num1 : num2;
    //从两个数的最小值开始递减遍历
    for (i = min; i > 0; i--)
    {
        //i为num1和num2的公倍数
        if (num1 % i == 0 && num2 % i == 0)
            break;
    }
    return i;
}

int main()
{
    int num1 = 0, num2 = 0;
    puts("请输入两个正整数.");
    scanf_s("%d%d", &num1, &num2);
    printf("最大公约数为%d.\n", Get_Max_Comm_Divisor(num1, num2));
    return 0;
}

The result of the operation is as follows:

Method Two:

         Roll and divide

1. If b == 0, the calculation ends, and a is the greatest common divisor;

2. Otherwise, calculate the remainder of dividing a by b, let a be equal to b, and b be equal to that remainder;

3. Go back to step 1

The code example is as follows:

#include <stdio.h>
int main(int argc, const char* argv[])
{
    int a;
    int b;
    int temp;
    scanf_s("%d %d", &a, &b);//低版本编译器使用scanf 高版本编译器使用scanf_s
    while (b != 0)
    {
        temp = a % b;
        a = b;
        b = temp;
    }
    printf("gcd = %d\n", a);
    return 0;
}

The result of running the code is as follows:

 Method three:

        more detrimental method

       1. Find the difference diff between two positive integers num1 and num2;

       2. Assign num2 to num1, and let the subtrahend num2 in the last subtraction be the minuend in the next subtraction.

          At the same time, the current difference diff is used as the subtrahend for the next subtraction.

          In this way, we continue to subtract until the difference is 0. At this time, the divisor num2 is the greatest common factor we require

The code example is as follows:

#include <stdio.h>
int Get_Max_Comm_Divisor(int num1, int num2)
{
    //两数相减的结果(取正值)
    int diff = num1 > num2 ? num1 - num2 : num2 - num1;
    while (diff != 0)
    {
        num1 = num2;   //更新被减数
        num2 = diff; //更新减数
        diff = num1 > num2 ? num1 - num2\
            : num2 - num1; //更新两数相减的结果(取正值)
    }
    return num2;  //最后的减数即为最大公因数
}

int main()
{
    int num1 = 0, num2 = 0;
    puts("请输入两个正整数.");
    scanf_s("%d%d", &num1, &num2);//低版本编译器用scanf 高版本编译器用scanf_s
    printf("最大公约数为%d.\n", Get_Max_Comm_Divisor(num1, num2));
    return 0;
}

The result of running the code is as follows:

Method four:

Stein algorithm function recursive call

#include "stdio.h"
#include <windows.h>
int gcd(int u, int v)
{
    if (u == 0)	return v;
    if (v == 0)	return u;
    if (~u & 1)
    {
        if (v & 1)
            return gcd(u >> 1, v);
        else
            return gcd(u >> 1, v >> 1) << 1;
    }
    if (~v & 1)
        return gcd(u, v >> 1);
    if (u > v)
        return gcd((u - v) >> 1, v);
    return gcd((v - u) >> 1, u);
}
int main()
{
    int z[2][20] = { {1,1},{31,43,46,65,43,58,55,54,55,56,98,78,96,54,78,85,57,12,36,15} };
    int i = 0;
    double run_time;
    LARGE_INTEGER time_start;	//开始时间
    LARGE_INTEGER time_over;	//结束时间
    double dqFreq;		//计时器频率
    LARGE_INTEGER f;	//计时器频率
    int m, n, t2;
    getch();
    QueryPerformanceFrequency(&f);
    dqFreq = (double)f.QuadPart;
    QueryPerformanceCounter(&time_start);	//计时开始
    for (i = 0; i < 20; i++) {
        t2 = gcd(z[0][i], z[1][i]);
        printf("The higest common divisor is %d\n", t2);
    }
    QueryPerformanceCounter(&time_over);	//计时结束
    run_time = 1000000 * (time_over.QuadPart - time_start.QuadPart) / dqFreq;
    //乘以1000000把单位由秒化为微秒,精度为1000 000/(cpu主频)微秒
    printf("\nrun_time:%fus\n", run_time);
    return 0;
}

Stein algorithm non-function recursive call

#include "stdio.h"
#include <windows.h>
int Stein(int x,int y)
  /*return the greatest common divisor of x and y*/
{
	int factor=0;
	int temp;
if(x<y)
	{
		temp=x;
		x=y;
		y=temp;
	}
if(0==y)
	{
		return 0;
	}
while(x!=y)
	{
	if(x&0x1)
		{
		if(y&0x1)
		{
			y=(x-y)>>1;
			x-=y;
		}
		else
		{
			y>>=1;
		}
	 } 
else
 {
 	if(y&0x1)
	{
	 	x>>=1;
		if(x<y)
	 	{
	 	temp=x;
	 	x=y;
	 	y=temp;
		}
	}
	else
	{
	 	x>>=1;
		y>>=1;
	 	++factor;
		}	
 	}
	} 
return (x<<factor);
}
int main()
{
	int z[2][20] = {
   
   {1,1},{31,43,46,65,43,58,55,54,55,56,98,78,96,54,78,85,57,12,36,15}};
	int i = 0;
	double run_time;
	LARGE_INTEGER time_start;	
	LARGE_INTEGER time_over;	
	double dqFreq;		
	LARGE_INTEGER f;	
	int m,n,t2;
getch();
  QueryPerformanceFrequency(&f);
	dqFreq=(double)f.QuadPart;
	QueryPerformanceCounter(&time_start);	
	for( i = 0; i < 20; i++){
		t2 = Stein(z[0][i],z[1][i]);
		printf("The higest common divisor is %d\n",t2);
	}
	QueryPerformanceCounter(&time_over);	
	run_time=1000000*(time_over.QuadPart-time_start.QuadPart)/dqFreq;
	printf("\nrun_time:%fus\n",run_time);
	return 0;
} 

The code operation effect is as follows:

Editor's note: The above-mentioned various methods of writing code for this topic are welcome to collect, learn from and forward;

               The above code is for reference only, if you have any questions, you are welcome to criticize and correct in the message area;

               All rights reserved, reprints must be investigated, any similarity is purely coincidental, please indicate the source for reprinting.

               By CRH380AJ2808 2022.04.23
————————————————
Copyright statement: This article is the original article of CSDN blogger "CRH380AJ2808", following the CC 4.0 BY-SA copyright agreement, please attach the original text for reprinting Source link and this statement.
Original link: https://blog.csdn.net/JH13thpig/article/details/124361837

Guess you like

Origin blog.csdn.net/JH13thpig/article/details/124362053