Learn algorithms with Go @ recursive call

The purpose is to understand Go basic syntax and algorithm brain training.

About the algorithm

What is a recursive call?

Calling yourself in the process is called a recursive call, and that function is called a recursive function .

What is Euclidean algorithm?

An algorithm that finds the greatest common divisor of two integers. I will quote the method. > Let the input be m, n (m ≧ n). If n = 0, output m and exit the algorithm. The remainder of dividing m by n is newly set as n, and the original n is newly set as m, and the process returns to 2. >> Quote: https://ja.wikipedia.org/wiki/%E3%83%A6%E3%83%BC%E3%82%AF%E3%83%AA%E3%83%83%E3%83 % 89% E3% 81% AE% E4% BA% 92% E9% 99% A4% E6% B3% 95

Sample code 1

I will put the code for the time being.

package main

import "fmt"

func main() {
	num := 5
	fmt.Printf("From 1%Sum up to d:%d", num, calc(num))
}

func calc(a int) int {
	if a == 0 {
		return 0
	}
	result := a + calc(a-1)
	return result
}

Brief explanation

Code that calculates the sum from 0 to the number passed as an argument. The process of calling the calc function again in the calc function is being performed.

The process of exiting the recursive function is indispensable as shown below. Without this, you would end up in an infinite loop. This process is called the process for the base case.

    if a == 0 {
        return 0
    }

Sample code 2

I will put the code for the time being.

package main

import "fmt"

func main() {
	//num := 5
	num := [...]int{15, 51}
	fmt.Printf("%d and%Greatest common divisor of d:%d", num[0], num[1], calc(num[0], num[1]))
}

func calc(a, b int) int {
	if b == 0 {
		return a
	}
	result := calc(b, a%b)
	return result
}

Brief explanation

It uses the Euclidean algorithm.

Impressions

I have a severe caffeine addiction. If you don't drink coffee, you won't be able to work after the afternoon.

Recommended Posts

Learn algorithms with Go @ recursive call
Learn algorithms with Go @ Full search_Linear search method
Python with Go
Learn about Go slices
Call your own C library with Go using cgo
Learn Python with ChemTHEATER
Learn Service Bus Queue with Azure SDK for Go (1)
Learn Zundokokiyoshi with LSTM
Learn Pandas with Cheminformatics
Learn with chemoinformatics scikit-learn
Learn with Cheminformatics Matplotlib
Call bash with golang
Learn with Cheminformatics NumPy
DCGAN with TF Learn
Learn Pendulum-v0 with DDPG
Draw Bezier curves with Go
Learn librosa with a tutorial 1
Operate Db2 container with Go
Getting Started with Go Assembly
Bit full search with Go
Implement recursive closures in Go
Connect to Postgresql with GO
Learn elliptical orbits with Chainer
Hot reload with Go + Air
Learn new data with PaintsChainer
Try implementing perfume with Go
Call the API with python3.