It's Only Factorials

Do the following snippets of code always return the same output given a positive integer input?

1
2
3
4
5
def factorial(n):   
   factorial = 1   
   for number in range (1, n):   
      factorial = factorial * number   
   return factorial

1
2
3
4
5
def factorial(n):   
   if n == 1 :   
      return 1   
   else:   
      return n*factorial(n-1)   

Yes, always No, not always

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

1 solution

Arulx Z
Dec 11, 2015

The function xrange(x, y) is inclusive of x x while exclusive of y y . So the function only loops until y 1 y-1 .

Hence the first code return ( n 1 ) ! (n-1)! while the second code return n ! n! .

Moderator note:

Great! When coding, it is important to know what all of the terms mean, instead of just guessing at what they are.

The question does state "given a positive integer input".

Calvin Lin Staff - 5 years, 6 months ago

Log in to reply

Oh. I missed that. I found the flaw. I've fixed my answer. I just got a little lucky :p.

Arulx Z - 5 years, 6 months ago

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...