python - Calculating GCD - how to check every element in list -


  • multiple number inputs

below how chose start writing code

def main():  numbers = input() if numbers == "0":     exit() else:     number_list = [int(i) in numbers.split()]  def calculate_gcd(number_list):     in range(1,smallest_number(number_list)+1):         n in range(0,len(number_list)):             if number_list[n] % == 0:                check_list += number_list[n]  more code - not important question im asking code hardly complete , worked max 3 size lists, sadly. 

how thought of logic

  1. read input -> split space, put in list
  2. sort list
  3. make variable (divisor), , set 1
  4. while divisor <= sortedlist[0] (which smallest in list) 5. if every element % divisor == 0, gcd = divisor, divisor+=1
  5. loop until no longer true

problem found

  1. it requires stupid effort, not run , give runtime error.
  2. i'm having trouble finding way check no.5 (in bold) know there gcd function, deals 2 inputs. , comes down same question, how make sure 'all' elements divides down zero?

any suggestion of making gcd logic , comment on no.5 (bold) ?

thank you

instead of tackling bigger problem, why not tackle smaller problem. how find gcd of 2 numbers? well, there multiple algorithms this. let use iterative one:

def gcd_iterative(a, b):     while b:         a, b = b, % b     return 

now, 1 thing realize that, if have multiple numbers, , want find gcd of numbers, simply:

gcd(gcd(...(a, b), c), ...) 

in simpler terms, if want find gcd of 3 numbers (a, b, c), following:

gcd = gcd_iterative(a, b)  gcd = gcd_iterative(gcd, c) 

so, if have list of numbers, lst, can following:

>>> gcd = lst[0] >>> num in lst[1:]:         gcd = gcd_iterative(gcd, num) >>> print(gcd) 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -