Factorial Series of thehuxley.com site

9

Make a program that computes and writes the sum of the n first terms of the series:

seriefatorial http://www.thehuxley.com/data/images/app/ problems / temp / e68085c6d699d2c7029907f994c57b80.png

Input format An integer n indicating the number of terms in the series

Output format A floating-point number formatted to two decimal places, followed by one end of the line.

Input example: 5 Exit: 3.46

This question is from thehuxley.com site, when submitting the issue for this error: "The result of the evaluation was 'WRONG_ANSWER' which means your program did not return the expected response."

I have already done several tests with larger values and the result is as expected ... I have no idea what the test case is generating the wrong value. Anyone know?

def fatorial(number):
    if number == 0:
       return 1
    else:
       return number * fatorial(number - 1)

n = int(input())
count, value = 0, 0

for number in range(1, n + 1):
   count += count + 1   

   if(number % 2 == 0):  # par
       value -= fatorial(number) / count
   else:
       value += fatorial(number) / count

print("%.2f" % value)
    
asked by anonymous 04.05.2014 / 05:22

2 answers

2

These questions where you accumulate the result of several divisions between floating points can accumulate small errors of precision until a moment where it becomes significant. So, depending on how the language handles the floating point, the response may vary slightly between them. I emailed the website staff and they reviewed the test cases. They said that there were actually some cases that depending on the combination of C, Pascal, Java, Python and the type used to handle float, double, long double the result could be slightly different. They said they changed test cases to avoid such situations. After that, I took the liberty to get your solution and submit it to the site and the result was CORRECT.

    
11.05.2014 / 04:52
7

Your problem is that both the return of fatorial and count are integers. In Python 2, when one integer is divided by another, the result is always an integer:

>>> 3/2
1
>>> 3.0/2
1.5
>>> 3/2.0
1.5

While in Python 3 the result is a float . Your code - especially the use of parentheses after print - suggests that you are using 3, but nothing prevents the site from using 2.

To solve, simply change the function fatorial to return the result in floating point:

def fatorial(number):
    if number == 0:
       return 1.0
    ...

And - if necessary - put a line break at the end (such as suggested in comments ):

print("%.2f\n" % value)
    
04.05.2014 / 07:56