Calculating the factorials is one of the most basic algorithms out there. It’s so basic it’s actually used to teach a harder concept, recursion. I’m explaining this so that I can get away with using the 2-minute explanation of both concepts. Let me know if you’d be interested in a deeper dive.
Recursion, the repeated application of a recursive procedure i.e. a function calling itself. The joke goes “To understand recursion you must first understand recursion.”
A factorial of a number is the product of all positive integers less than or equal to that number. The thing with factorials, however, is that they tend to get very large very fast and the large the numbers the slower they perform.
For example
I wasn’t kidding about the 2 minute explanations.
Write an efficient function that calculates and displays extra long factorials.
A really long number that isn’t in exponential form
This honestly didn’t require much thought because it’s so easy. The first requirement to get large numbers. To do this all you have to do is cast your input to BigInt
and you’re gold.
BigInt(n)
or add an n
to the end of an integer literal, e.g. 1n
.
The second requirement is about efficiency. The biggest cause of the slowdown is that we calculate the factorials of lower numbers multiple times. This is a waste of time because the result is not going to change. So after the first calculation, we really shouldn’t be doing it again. As a result, if we cache those calculations, our performance goes up dramatically. This concept is called memoization and is a fun read.
function longFactorials(n) {
const cache = new Map()
const factorial = n => {
if (n == 0){
return 1n
}
if (cache.has(n)) {
return cache.get(n)
} else {
const x = BigInt(n) * factorial(n - 1)
cache.set(n, x)
return x
}
}
return factorial(n).toString()
}
Not too complicated right? This solution passes all tests didn’t kill any brain cells.
Today I am working on a summation problem made to look like building a tower out of cubic bricks. It’s fun to brute force sometimes.
Coming back to Rust code after a bit of a hiatus with a simple problem… The Two-sum problem. Finding numbers in an array. Yay, fun.
King Pinn: I Salute You. I’m driving halfway across the country and this song is on repeat. Rest in Peace Tonderai Makoni. You were awesome.
After a few weeks off I’m back to business. This is just an update post detailing plans for the rest of the year.
At last we finally have the great reveal, our mystery project was implementing RSA encryption in rust.