Monday, 03 November 2014 00:00

Lazily satisfying my curiosity

Written by Albert Sharkis
Rate this item
(0 votes)
This is the story all about how my life got flipped turned upside-down I forgot basic algebra and instead used my 2.2 GHz processor to brute force an answer to a question raised by Facebook. Yay technology!
While scrolling through my Facebook feed, I found this:

Normally I don't bother with this (and I still didn't read the article), but the image definitely piqued my interest. How much money would you have at the end of a year with this saving strategy? Now, if I had remembered my algebra, I'd have remembered this is a triangular number and use this formula to find the answer:
But this is America, dammit.
import sys

def sumseries(n):
	if n > 1:
		return n+sumseries(n-1)
	else:
		return 1

print(str(sumseries(int(sys.argv[1]))))

So I wrote a recursive function that manually adds a number with the result of the same function, all the way down to 1. So this would have generated 52 separate calls of the function and then worked its way back up the stack until I got my answer: $1378.
And that's why it's important to keep up-to-date on your maths.
I'd like to point out the name of my function was "sumseries". If I'd bothered to Google that I would have found the formula faster, which is why I always research these kind of things when it comes to client projects. This practice started when I was developing a part of an application involved with finding objects within a range of a user. Waaaaay back in 2010-2011, I ended up working on a whiteboard until I had derived a formula that dealt with the range and how latitude would appear to distort the longitude. What I had done was derive the Haversine formula.
Read 2593 times Last modified on Monday, 03 November 2014 18:42