This is my first post. It's been a week since I started doing python. I'm still a chick, so I'm practicing with the problem collection I found online.
I will leave an article as a memorandum because the problem I found at that time could not be solved well.
This is a must-see for super beginners! !! !!
Simply put, a calculation method that can mechanically obtain the greatest common divisor.
Method of calculation ① Prepare two natural numbers you want to check ② Large ÷ small (3) If there is a remainder, the smaller number and its greatest common divisor match the greatest common divisor of the original two numbers. ④ By repeating this, you can find the greatest common divisor with simple numbers.
Well it looks like this. I'm sorry it's hard to understand.
Now let's write the code. First, define a new function gcd ()
def gcd(a,b) #Define function
Use def to define the function yourself.
Next, let's write the processing that this function does. In Euclidean algorithm, the calculation has to be repeated many times. Therefore, the following conditional branching is required.
① When there is no remainder (when it is divisible), the calculation ends there. ② If there is a remainder, continue the calculation
The processing is divided according to the two cases. In other words, you should use if!
Therefore, I think the code will look like the one below.
def gcd(a,b) #Define function
#At the time of ①
if b == 0
return a
#At the time of ②
else:
return gcd(b,a%b)
This is the end of writing! !! !! After that, it seems that you should use the input function and add the print function to output the result so that you can freely input your favorite 2 numbers. ↓ is the completed form.
a,b = input(),input()
#Convert to integer
a,b = int(a),int(b)
#Define function
def gcd(a,b)
#At the time of ①
if b == 0
return a
#At the time of ②
else:
return gcd(b,a%b)
#Output result
print(gcd(a,b))
That's all there is to it! !!
This time, the Euclidean algorithm is expressed in python.
At first, the input didn't work and I got an error, but when I attached the int, it worked. ~~ I'm not sure why, so I'd be happy if you could tell me about that. ~~
Addition I told you in the comments! The reason seems to be the difference in type. input is str because it is a function that receives the "string" entered by the user. On the other hand, the type assumed by the gcd function is int, so the types do not match and an error occurs. In other words, if you convert it to an integer with the int function, it will work.
Additional notes I told you in the comments again! If you have python 3.5 or later, it seems that the math library has a function like I made!
Thank you for reading until the end! !! !! Feel free to give me any advice!
Recommended Posts