Algorithm #1

gyu·2024년 3월 9일

Algorithm

목록 보기
1/45

1) Complete the solution function to take two integer parameters, num1 and num2, and return the quotient of num1 divided by num2

def solution(num1, num2):
    answer = num1 // num2
    return answer
  • Floor division operator (//)
    division operation that rounds the result down to the nearest whole number or integer, which is less than or equal to the normal division result.

2) Given two integers, num1 and num2, please complete the solution function to return the integer part of the result obtained by multiplying num1 by num2 and then dividing the result by 1,000

def solution(num1, num2):
    answer = int((num1 / num2) * 1000)
    return answer
  • int()
    converts the specified value into an integer number

3)You are given the parameters numer1 and denom1, representing the numerator and denominator of the first fraction, and numer2 and denom2, representing the numerator and denominator of the second fraction. Complete the solution function to return an array containing the numerator and denominator of the simplified fraction obtained by adding these two fractions.

def solution(numer1, denom1, numer2, denom2):
    answer = []
    if denom1 != denom2:
        denom = denom1 * denom2
        numer = denom1 * numer2 + denom2 * numer1
    else:
        denom = denom1
        numer = numer1 + numer2 
    # Find gcd of them
    for i in range(1, denom+1):
        if(denom % i == 0 ) & (numer % i == 0):
            gcd = i
    # divide both the numerator and denominator by GCD
    denom = denom / gcd
    numer = numer / gcd
    #return [numerator, denominator]
    answer.append(numer)
    answer.append(denom)
    return answer
  • GCD(The greatest common divisor)
    I know 2 ways to find the gcd in python
  1. Using for loop
for i in range(1, denom+1):
    if(denom % i == 0 ) & (numer % i == 0):
          gcd = i
  1. Using Math module
    Syntax: math.gcd(x, y)
import math

gcd = math.gcd(denom, numer)
profile
#TechExplorer 🚀 Curious coder exploring the tech world, documenting my programming journey in a learning journal

0개의 댓글