C language - recursive implementation of Euclidean algorithm for finding the greatest common divisor

This code can be divided into the following parts for analysis:

  1. Function definition part:

    int app(int a,int b)
    {
      if(b==0)
      {
        return a;
      }
      else
      {
        return app(b,a%b);
      }
    }
    

    This part defines a function namedapp, which is used to calculate the greatest common divisor of two integers. It uses a recursive implementation of Euclidean's algorithm. The function accepts two integer parameters a and b. If b is equal to 0, it returns a as the greatest common divisor; otherwise call the app function recursively, passing b as a new parameter to a, < a i=9> is passed to as a new parameter until the recursion termination condition is met. a%bb

  2. Main function part:

    int main()
    {
      int a,b,sum=0;
      printf("输入两个数字,(以空格为分隔符):");
      scanf("%d %d",&a,&b);
      sum=app(a,b);
      printf("最大公约数为:%d",sum);
      return 0;
    }
    

    This part is the entry function of the programmain, and the program starts execution from here. Three integer variables a, b and sum are defined in the main function, which are used to store the two numbers entered by the user. and the greatest common divisor. Prompt the user for two numbers by using the printf function, and read the two numbers from the user input using the scanf function. Then call the app function to calculate the greatest common divisor and assign the result to the sum variable. Finally, use theprintf function to output the value of the greatest common divisor. The program ends with the return 0 statement, indicating that the program has been executed normally.

The function of this code is to calculate and output the greatest common divisor of two numbers. The user needs to input two numbers when the program is running, and then the program calculates the greatest common divisor of the two numbers by calling the app function and outputs the result to the user.

This code is a complete program to find the greatest common divisor of two integers.

In the main function, two integer variables a and b are first defined, and then the scanf function is used to obtain the Read these two numbers from the user input.

Next, call the app function to calculate the greatest common divisor and save the result in the sum variable.

Finally, use theprintf function to output the value of the greatest common divisor.

This code runs fine and calculates the greatest common divisor of two numbers entered by the user and outputs the result to the user.

#include<stdio.h>
int app(int a,int b)
{
	if(b==0)
	{
		return a;
	}
	else
	{
		return app(b,a%b);
	}
}
int main()
{
	int a,b,sum=0;
	printf("输入两个数字,(以空格为分隔符):");
	scanf("%d %d",&a,&b);
	sum=app(a,b);
	printf("最大公约数为:%d",sum);
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_66547608/article/details/134708198