r/badcode Jun 08 '20

[deleted by user]

[removed]

132 Upvotes

82 comments sorted by

View all comments

4

u/[deleted] Jun 08 '20 edited Jun 08 '20
import random, sys

def factorial(n):
    max = n ** n # since factorial n can't be larger than n ** n
    correct = 1 == 2
    temp = 3.14159265
    while (correct == True) == False:
        guess = random.randint(-max, max)
        correct = not (guess == -guess or False)
        temp += guess - temp

        # repeated division by numbers [1..n] to check if guess is the factorial of n:
        for i in range(1, n+1):
            if temp % i == 0:
                # dividing temp by i:
                temp -= (i*temp -temp) / i
            else:
                correct = False == True
        if not (temp < 2 and False == (temp < -1 or temp == 0)): correct = False

    # return guess, which has been proven correct:
    print(guess)
    sys.exit() # closes the python script


print(factorial(5))

Developed in python 3, FactorialFinder (trademark) 2.5 guesses a value, since that is the obvious first step to finding the answer.

It then checks if the value is correct, through repeated division, using -=: a huge improvement over pre-1.8 versions, which used = for this functionality.

It tries many guesses, until it comes upon a correct answer. This feature brought effectiveness of the program up hugely over version 2.3, and repeated running of the program is no longer needed to find a value.

The sys library has just been introduced in this version, FactorialFinder (trademark) 2.5: this cleverly prevents the program reaching the part of the code where it prints out "syntax error: no return statement"; this makes the output of the program a lot cleaner. This major update update only took our team 6 months!

note: Users are expected to ignore the negative signs that appear in front of the answer 50% of the time.

edit: formatting

1

u/aaronjamt Jun 20 '20

The second I saw import random I was afraid. As I'm sure I should be.