DEV Community

Durga Pokharel
Durga Pokharel

Posted on

Day 4 of 100DaysOfCode: Code to Calculate HCF Of Two Numbers

Today is my 4rth day of coding. Today I gave my time for file handling. I have been so much confused. I am not clear about some concept of it yet. Today I also did some code on function, dictionary in some mathematical problem. I gave some time of mine to the Freecodecamp and Coursera too.
Below is the code of mine for today, which I wrote to find the HCF of two numbers. For this code, I used a function to do the job. At first, I asked the user to input two numbers integer type. Then I find the maximum and minimum of these two numbers. I created an empty list name of CF to store a common factor. I started looping from 1 to the minimum number. Because the possibility of HCF will be from 1 to a minimum among these two numbers. Below is my code.

def higher_common_factor():
    n1 = int(input('enter the number'))
    n2 = int(input('enter the number'))
    m1 = min(n1,n2)
    m2 = max(n1,n2)
    cf = []
    for n in range(1,m1+1):
        if m1 % n == 0 and m2 % n ==0:
            cf.append(n)
    print(f"{cf}")
higher_common_factor()
Enter fullscreen mode Exit fullscreen mode

#100DaysOfCode, day4
* Learn about python
* HCF of two numbers
* Learn about python function#Python #CodeNewbie #beginner #functon pic.twitter.com/5ZkQCUxYmk

— Durga Pokharel (@mathdurga) December 27, 2020

Top comments (4)

Collapse
 
otumianempire profile image
Michael Otu • Edited

Your program returns the Common Factors of two numbers. A list actually..

enter the number: 135
enter the number: 45
[1, 3, 5, 9, 15, 45]  # the common factors

enter the number: 19
enter the number: 0
[] 
Enter fullscreen mode Exit fullscreen mode

0 is expected.

it should return a number. Use print(f"{max(cf)}")

Collapse
 
iamdurga profile image
Durga Pokharel

Thanks for the suggestion.🙂

Collapse
 
nitinkatkam profile image
Nitin Reddy

File handling in Python is actually quite simple.

Look at this example of reading a file in 2 lines of code:

with open('myfile.txt') as myfilereader:
  txt = myfile.read()
print(txt)
Enter fullscreen mode Exit fullscreen mode

Apart from Python, Ruby is quite easy to learn and is arguably simpler.

Collapse
 
iamdurga profile image
Durga Pokharel

Really? I am learning python to understand code workflow.