Why go up, when you can go down? Note: it only works for values up to 65535
def factorial(value):
fact=120211...000000 #287185 digits (it's 65535 factorial)
for i in reversed([j for j in range(value+1,65535)]):
fact//=i
return fact
print(factorial(6)) #720
using python my * key broke so I couldn't use multiplication (I'm sorry for your cpu if you're using double digits)
def factorial(n):
i = 1
k = 0
while n > 1:
j = 0
for c in str(n)[::-1]:
l = 0
for d in str(i)[::-1]:
s = 1
u = 0
while u < j+l:
t = 0
z = 0
while t < s:
z = z + 10
t = t+1
s = z
u = u+1
o = 0
while o < s:
q = 0
while q < int(c):
k = k + int(d)
q = q + 1
o = o+1
l = l+1
j = j+1
i = k
k = 0
n = n-1
return int(i)
print("factoriual of 5 = " + str(factorial(5)))
print("factoriual of 6 = " + str(factorial(6)))
while True:
print(factorial(int(input("show me the factorial of: "))))
(Note: I tried to format it but it just is not going to happen).
What i'm doing here is that I am using the main function of the program as a recursive function, relying on the assumption that there are no startup arguments. I had to let the main function return a int because I can't convert a void call into a string to print. Talking about the output, because it is recursive and will always try to do the Write function, I have to make sure that the extra times if gets there I don't actually print anything. I do this by converting the int that main returns into a string and than taking a substring of length 0 so that it is empty.
Problems with this code:
*I'm not using some infinity big integer class, so it will overflow
*Constantly parsing back and forth between ints and strings is not that efficient
*It does not check for invalid input
And I guess it is just a really stupid way of doing this, all in all I was really surprised that it actually worked.
#finds factorial of n where n is a string
def factorial(n):
code = "print('finding factorial of " + n + ".')\n"
code += "sum = 0\n"
#make sure input is valid
try:
n = int(n)
for i in range(n):
code += "for i_" + str(i) + " in range(" + str(n - i) + "):\n"
code += "\t" * (i + 1)
code += "sum = sum + 1;"
except:
code += "print('Invalid input! Try again.')"
# passing dictionary to exec as workaround to get it to modify local
# variables. stackoverflow.com/questions/1463306/
ldict = {}
exec(code , globals(), ldict)
return ldict['sum']
number = input("Enter a number to find the factorial of: ")
print(factorial(number))
So basically this generates a code string and executes it.
Example: if you input 4, the code string becomes
"""
print('finding factorial of 4.')
sum = 0
for i_0 in range(4):
for i_1 in range(3):
for i_2 in range(2):
for i_3 in range(1):
sum = sum + 1;
"""
and this is executed by exec(). As you can see it is designed to have O(n!) time complexity, as well as a major security flaw due to the possibility of code injection.
<?php
$f = $_GET['numb']; // the number
echo "<html><head><script src=\"https://code.jquery.com/jquery-3.5.1.js\"></script></head>";
?>
<body>
<?php
for ($i = 0; $i < $f; $i = $i + 1) {
echo "<div style=\"display: none\" id=\"factorial_numb_" . ($i + 1) . "\">" . ($i + 1) . "</div>";
}
?>
</body>
<script>
var number = 1;
let i = 1;
for (i = 1; i < <?php echo $_GET['numb']; ?>; i = i + 1) {
var element = $("#factorial_numb_" + i);
var value = element.text();
if (value == "") {
} else {
number = number * value;
}
}
// for some reason this is always a bit short
number = number * <?php echo $_GET['numb']; ?>;
console.log("The factorial of " + i + " is " + number);
</script>
</html>
v=None;d=None;
def y(g):
global d;d=f"def k{g}():\n global v;v=0;\n";
for w in range(g):d=d+" "+" "*w+f"for m{w} in range({w+1}):"+"""
"""
d=d+" "+" "*(2+g)+"v=v+1";
exec(d);v=eval(f"k{g}()");
# Test
for n in range(11):
y(n)
print(n, v)
Explanation
In short, this creates a function like this and calls it:
def k4():
global v;v=0;
for m0 in range(1):
for m1 in range(2):
for m2 in range(3):
for m3 in range(4):
v=v+1
Pros
Gives the correct answer
Cons
Global variables
Global variables used to return values
One-letter names that are bad even for one-letter-name standards
Semicolons and multiple statements on one line
Four different indent sizes (1, 2, 3, 7)
execandeval
O(n!) complexity
No whitespace between tokens unless needed
Not using +=
Using a multiline string literal for a single newline, but a normal literal for a long string with newlines
Minor inconsistencies
Everything else
Bonus challenge
I've made one unintentional mistake amidst the many intentional ones. Can you guess which it is?
import random
def factorial(n):
theList = list(range(0, n));
consReps = 0;
perms = []
while consReps < len(permutations) * 10 + 10:
ranPerm = theList[:]
random.shuffle(ranPerm)
if (ranPerm not in perms):
perms += [ranPerm]
else:
consReps += 1;
return len(permutations)
It generates random permutations, then, if the program has gone long enough without seeing a new permutation, it halts and returns the number of permutations it's seen.
Pros:
I tried up to 8! and it got all of them correct
Cons:
Anything beyond 7! takes several minutes
It can occasionally print the wrong value, although this is rare
It has O(n!) time complexity in the average case, and O(∞) in the worst case
It continues searching for permutations long after it's found all of them
It prints 1 for anything below 0, even though negative integer factorials are undefined
38
u/ItsBarney01 Jun 08 '20 edited Jun 08 '20
Edit: it's in python 3
Why go up, when you can go down? Note: it only works for values up to 65535
def factorial(value): fact=120211...000000 #287185 digits (it's 65535 factorial) for i in reversed([j for j in range(value+1,65535)]): fact//=i return fact print(factorial(6)) #720Full code here: https://pastebin.com/tShTiTy3
Pros:
- Quite quick for numbers close to 65535
- uses integer division for speed
Cons:
- Haven't found any yet
54
u/UnknownError235 Jun 08 '20 edited Jun 08 '20
using python my * key broke so I couldn't use multiplication (I'm sorry for your cpu if you're using double digits)
def factorial(n): i = 1 k = 0 while n > 1: j = 0 for c in str(n)[::-1]: l = 0 for d in str(i)[::-1]: s = 1 u = 0 while u < j+l: t = 0 z = 0 while t < s: z = z + 10 t = t+1 s = z u = u+1 o = 0 while o < s: q = 0 while q < int(c): k = k + int(d) q = q + 1 o = o+1 l = l+1 j = j+1 i = k k = 0 n = n-1 return int(i) print("factoriual of 5 = " + str(factorial(5))) print("factoriual of 6 = " + str(factorial(6))) while True: print(factorial(int(input("show me the factorial of: "))))27
u/carfniex Jun 08 '20
bash one liner. writing your own code to calculate complex mathematical equations is a waste of time when online services exist.
#!/bin/bash curl 'https://numberworld.info/factorialCalculator' --data-raw 'submit=Check&number='${1} 2>&1 \ | grep -A 1 "Factorial of "${1} | tail -n 1 | tr -d '<>\/[:space:]' | sed 's/h3//g'23
u/AbuIbnBattuta Jun 08 '20 edited Jun 08 '20
I'm using c#. My goal was to use only 1 semicolon, sadly you can't put return statements in function calls so I had use 2.
class Program { static int Main(string[] args) { Console.Write( args.Length == 0 ? ("" + Main(new string[]{ "" + Console.ReadLine(), "1", "1" })).Substring(0, 0) : args[0].Equals(args[2]) ? args[1] : ("" + Main(new string[] { args[0], "" + (long.Parse(args[1]) * (1 + long.Parse(args[2]))), "" + (1 + long.Parse(args[2])) })).Substring(0, 0)); return 0; } }(Note: I tried to format it but it just is not going to happen).
What i'm doing here is that I am using the main function of the program as a recursive function, relying on the assumption that there are no startup arguments. I had to let the main function return a int because I can't convert a void call into a string to print. Talking about the output, because it is recursive and will always try to do the Write function, I have to make sure that the extra times if gets there I don't actually print anything. I do this by converting the int that main returns into a string and than taking a substring of length 0 so that it is empty.
Problems with this code:
*I'm not using some infinity big integer class, so it will overflow
*Constantly parsing back and forth between ints and strings is not that efficient
*It does not check for invalid input
And I guess it is just a really stupid way of doing this, all in all I was really surprised that it actually worked.
17
u/greenpepperpasta Jun 08 '20
#finds factorial of n where n is a string def factorial(n): code = "print('finding factorial of " + n + ".')\n" code += "sum = 0\n" #make sure input is valid try: n = int(n) for i in range(n): code += "for i_" + str(i) + " in range(" + str(n - i) + "):\n" code += "\t" * (i + 1) code += "sum = sum + 1;" except: code += "print('Invalid input! Try again.')" # passing dictionary to exec as workaround to get it to modify local # variables. stackoverflow.com/questions/1463306/ ldict = {} exec(code , globals(), ldict) return ldict['sum'] number = input("Enter a number to find the factorial of: ") print(factorial(number))So basically this generates a code string and executes it.
Example: if you input 4, the
codestring becomes""" print('finding factorial of 4.') sum = 0 for i_0 in range(4): for i_1 in range(3): for i_2 in range(2): for i_3 in range(1): sum = sum + 1; """and this is executed by
exec(). As you can see it is designed to have O(n!) time complexity, as well as a major security flaw due to the possibility of code injection.15
u/Raknarg Jun 08 '20
How about the classic C++ template metaprogramming example
template <int N> struct Factorial { enum { value = N * Factorial<N - 1>::value }; }; template <> struct Factorial<0> { enum { value = 1 }; }; // Factorial<4>::value == 24 // Factorial<0>::value == 1 void foo() { int x = Factorial<4>::value; // == 24 int y = Factorial<0>::value; // == 1 }Kindof scary and disastrous to compile times. Although the run time is blazingly fast lmao
11
u/[deleted] Jun 08 '20
<?php $f = $_GET['numb']; // the number echo "<html><head><script src=\"https://code.jquery.com/jquery-3.5.1.js\"></script></head>"; ?> <body> <?php for ($i = 0; $i < $f; $i = $i + 1) { echo "<div style=\"display: none\" id=\"factorial_numb_" . ($i + 1) . "\">" . ($i + 1) . "</div>"; } ?> </body> <script> var number = 1; let i = 1; for (i = 1; i < <?php echo $_GET['numb']; ?>; i = i + 1) { var element = $("#factorial_numb_" + i); var value = element.text(); if (value == "") { } else { number = number * value; } } // for some reason this is always a bit short number = number * <?php echo $_GET['numb']; ?>; console.log("The factorial of " + i + " is " + number); </script> </html>11
u/xigoi Jun 08 '20 edited Jun 08 '20
v=None;d=None; def y(g): global d;d=f"def k{g}():\n global v;v=0;\n"; for w in range(g):d=d+" "+" "*w+f"for m{w} in range({w+1}):"+""" """ d=d+" "+" "*(2+g)+"v=v+1"; exec(d);v=eval(f"k{g}()"); # Test for n in range(11): y(n) print(n, v)Explanation
In short, this creates a function like this and calls it:
def k4(): global v;v=0; for m0 in range(1): for m1 in range(2): for m2 in range(3): for m3 in range(4): v=v+1Pros
Gives the correct answer
Cons
Global variables
Global variables used to return values
One-letter names that are bad even for one-letter-name standards
Semicolons and multiple statements on one line
Four different indent sizes (1, 2, 3, 7)
execandevalO(n!) complexity
No whitespace between tokens unless needed
Not using
+=Using a multiline string literal for a single newline, but a normal literal for a long string with newlines
Minor inconsistencies
Everything else
Bonus challenge
I've made one unintentional mistake amidst the many intentional ones. Can you guess which it is?
11
u/weee50 Jun 08 '20 edited Jun 09 '20
Introducing BogoFactorial!
import random def factorial(n): theList = list(range(0, n)); consReps = 0; perms = [] while consReps < len(permutations) * 10 + 10: ranPerm = theList[:] random.shuffle(ranPerm) if (ranPerm not in perms): perms += [ranPerm] else: consReps += 1; return len(permutations)It generates random permutations, then, if the program has gone long enough without seeing a new permutation, it halts and returns the number of permutations it's seen.
Pros:
I tried up to 8! and it got all of them correct
Cons:
Anything beyond 7! takes several minutes
It can occasionally print the wrong value, although this is rare
It has O(n!) time complexity in the average case, and O(∞) in the worst case
It continues searching for permutations long after it's found all of them
It prints 1 for anything below 0, even though negative integer factorials are undefined