Closed code-reaper08 closed 3 years ago
Hey code-reaper08 That list index out of bound is due to reason:
Check this out :)
import math def gcd(m,n): fm = [] fn = [] cf = [] for i in range(1,m): if (m % i) == 0: fm.append(i) # add to fm for i in range(1,n): if ( n % i) == 0: fn.append(i) # add to fn for f in fm: if f in fn: cf.append(f) # add to cf return(math.prod(cf)) # driver code print(gcd(18,76))
Looks cool 😎 Will check it out and replace the necessary.
Awesome @Chandu71202
Looks cool 😎 Will check it out and replace the necessary.
Hey @Chandu71202 😄
I made this using single loop, the problem is elif
as you told, we won't need the math
module I guess.
we can use negative index as used in lecture.
def gcd(m,n):
fm = []
fn = []
cf = []
for i in range(1,max(m,n)): #single loop instead of two for loops.
if (m % i) == 0:
fm.append(i) # add to fm
if ( n % i) == 0:
fn.append(i) # add to fn
for f in fm:
if f in fn:
cf.append(f) # add to cf
return(cf[-1])
# driver code
print(gcd(18,76))
Now it works, look once in your system.
4acc428e35256b8b7162c1384cded8d58e475337
- And another point to consider we need the product of all common divisors of both number for GCD. not just the first element
@Chandu71202 I think product is not needed, we just need the largest common factor between m & n, so
import math
def gcd(m,n):
fm = []
fn = []
cf = []
for i in range(1,m):
if (m % i) == 0:
fm.append(i) # add to fm
for i in range(1,n):
if ( n % i) == 0:
fn.append(i) # add to fn
for f in fm:
if f in fn:
cf.append(f) # add to cf
return(math.prod(cf))
# driver code
print(gcd(98,56))
This gives me an output of 196
.
Whereas here we get GCD as
def gcd(m,n):
fm = []
fn = []
cf = []
for i in range(1,max(m,n)): #single loop instead of two for loops.
if (m % i) == 0:
fm.append(i) # add to fm
if ( n % i) == 0:
fn.append(i) # add to fn
for f in fm:
if f in fn:
cf.append(f) # add to cf
return(cf[-1])
# driver code
print(gcd(98,56))
This gives the GCD as 14
Ohh yeah code-reaper08. That's correct no need of using the product. And using a single for loop is too a getting a less space which was good. I think the updated one is good to go👌
I've added two more optimizations according to the lectures. You can have a look, there is an another open issue here #2 on addition of new algorithm too. You can work on that too if you wish :-)
Cheers !
I'll close this issue, since its solved 🥇
Getting list index out of bound in this line, on execution.