Without doubt, the most mathematically sophisticated television show in the history of primetime broadcasting is The Simpsons. This is not a figment of my deranged mind, which admittedly is obsessed with both The Simpsons and mathematics, but rather it is a concrete claim backed up in a series of remarkable episodes.

The first proper episode of the series in 1989 contained numerous mathematical references (including a joke about calculus), while the infamous "Treehouse of Horror VI" episode presents the most intense five minutes of mathematics ever broadcast to a mass audience. Moreover, The Simpsons has even offered viewers an obscure joke about Fermat's last theorem, the most notorious equation in the history of mathematics.

These examples are just the tip of the iceberg, because the show's writing team includes several mathematical heavyweights. Al Jean, who worked on the first series and is now executive producer, went to Harvard University to study mathematics at the age of just 16. Others have similarly impressive degrees in maths, a few can even boast PhDs, and Jeff Westbrook resigned from a senior research post at Yale University to write scripts for Homer, Marge and the other residents of Springfield.

When they moved from academia to Fox Studios, these writers retained their passion for numbers and they have secretly planted mathematical references in dozens of episodes. Until now, only extreme geeks have been aware that the writers have been smuggling mathematics into their scripts while the rest of the planet has been oblivious to the numerous nods to number theory and geometry.

The 2006 episode "Marge and Homer Turn a Couple Play", for example, contains a triple dose of secret mathematics. The storyline revolves around Marge and Homer's efforts to help baseball star Buck Mitchell and his wife Tabitha Vixx, who are experiencing marital difficulties. The episode climaxes with Tabitha appearing on the Jumbo Vision screen at the Springfield stadium, where she publicly proclaims her love for Buck. More important, just before she appears on the screen, it displays a question that asks the baseball fans in the crowd to guess the attendance.

The Jumbo Vision screen from 'Marge and Homer Turn a Couple Play', showing a perfect number, a narcissistic number and a Mersenne prime number.

The screen displays three multiple choice options; 8,128, 8,208 and 8,191. These digits might seem arbitrary and innocuous, but in fact they represent a perfect number, a narcissistic number and a Mersenne prime.

8,128 is called a perfect number, because its divisors add up to the number itself. The smallest perfect number is 6, because 1, 2 and 3 not only divide into 6, but they also add up to 6. The second perfect number is 28, because 1, 2, 4, 7 and 14 not only divide into 28, but they also add up to 28. The third perfect number is 496, and the fourth one is 8,128, which appears in this episode. As René Descartes, the 17th-century French mathematician (and philosopher) pointed out: "Perfect numbers, like perfect men, are very rare."

8,208 is a narcissistic number because it contains 4 digits, and raising each of these digits to the 4th power generates four numbers that add up to itself: 84 + 24 + 04 + 84 = 8,208.

The fact that 8,208 can recreate itself from its own components hints that the number is in love with itself, hence the narcissistic label. Among the infinity of numbers, fewer than 100 exhibit narcissism.

8,191 is a prime number, because it has no divisors other than 1 and the number itself, and it is labelled a Mersenne prime because another 17th-century French mathematician, Marin Mersenne, spotted that 8,191 was equal to 213 – 1. More generally, Mersenne primes fit the pattern 2p –1, where p is any prime number.

Not surprisingly, several of the mathematical quips in The Simpsons relate to Homer and Marge's daughter, Lisa. She is proud to be a nerd and her grasp of everything from trigonometry to logarithms is recognised by Principal Skinner in the episode "Treehouse of Horror X" (1999). After a stack of bench seats falls on Lisa, he cries out: "She's been crushed! And so have the hopes of our mathletics team."

In "MoneyBart", much of the episode is dedicated to Lisa's ruthlessly mathematical approach to coaching a winning baseball team. The entire storyline is rooted in statistics, but the most significant nerd reference appears and disappears in a blink of an eye. Just before her first big game in charge, we see Lisa poring over piles of technical books. This extraordinary sight prompts a reporter to remark: "I haven't seen this many books in a dugout since Albert Einstein went canoeing." Those who concentrate hard enough will spot that one of the books is titled "eiπ + 1 = 0". To the untrained eye, this is just another random equation. To the mathematical eye, this is the single most beautiful equation in history, because it combines five of the fundamental ingredients of mathematics (0, 1, e, i, and π) in one elegant recipe. It is known as Euler's identity, and named after the 18th-century Swiss genius Leonhard Euler.

When I met the writers in Los Angeles last year, they explained that this reference to Euler's identity is a perfect example of a freeze-frame gag, a form of humour that was largely developed by the show's writing team. Freeze-frame gags are visual quips that fly by unnoticed during the normal course of viewing, but which become more obvious when the programme is paused.

To some extent, the freeze-frame gag was a product of technological developments. Roughly 65% of American households owned a video recorder by 1989, when The Simpsons was launched. This meant that fans could watch episodes several times and pause a scene when they had spotted something curious. Also, in 1989 more than 10% of households had a home computer and a few people even had access to the internet. The following year saw the birth of alt.tv.simpsons, a usenet newsgroup that allowed fans to share, among other things, their freeze-frame discoveries.

The writers relished the notion of the freeze-frame gag, because it enabled them to increase the comedic density. The mathematicians on the show were doubly keen because freeze-frame gags also gave them the opportunity to introduce obscure references that rewarded the hard-core number nerds.

For example, "Colonel Homer" (1992) features the first appearance of the local movie theatre, and eagle-eyed viewers would have glimpsed that it is called the Springfield Googolplex. In order to appreciate this reference, it is necessary to go back to 1938, when the American mathematician Edward Kasner was in conversation with his nephew Milton Sirotta. Kasner casually mentioned that it would be useful to have a label to describe the number 10100 (or 10,000,000,000,000,000,000,000,000,000,000,000,000, 000,000,000,000, 000,000,000,000, 000,000,000,000,000,000,000,000,000,000,000,000,000). The nine-year-old Milton suggested the word googol.

In his book Mathematics and the Imagination, Kasner recalled how the conversation with his nephew continued: "At the same time that he suggested 'googol', he gave a name for a still larger number: 'googolplex'. A googolplex is much larger than a googol, but is still finite, as the inventor of the name was quick to point out. It was first suggested that a googolplex should be 1, followed by writing zeros until you get tired."

The uncle rightly felt that the googolplex would then be a somewhat arbitrary and subjective number, so he redefined the googolplex as 10googol. This represents a number that is 1 followed by a googol zeros, which is far more zeros that you could fit on a piece of paper the size of the observable universe, even if you used the smallest font imaginable.

These terms – googol and googolplex – have become moderately well known today, even among the general public, because the term googol was adopted by Larry Page and Sergey Brin as the name of their search engine. However, they preferred a common misspelling, so the company is called Google, not Googol. The name implies that the search engine provides access to vast amounts of information. Google headquarters is, not surprisingly, called the Googleplex.

Simpsons writer Al Jean, third from left in the back row, in the mathematics team from 1977 Roeper School yearbook. Photograph: Courtesy of Al Jean

Simpsons writer Al Jean recalls that the Springfield Googolplex freeze-frame gag was not in the original draft of the script for "Colonel Homer." Instead, he is confident that it was inserted during one of the collaborative rewrites, when the mathematical members of the team tend to exert their influence: "Yeah, I was definitely in the room for that. My recollection is that I didn't pitch Googolplex, but I definitely laughed at it. It was based on theatres that are called octoplexes and multiplexes. I remember when I was in elementary school, the smartass kids were always talking about googols. That was definitely a joke by the rewrite room on that episode."

Mike Reiss, a teenage mathematics prodigy who has worked with Jean on the show since the first season, thinks that the Springfield Googolplex was possibly his freeze-frame gag. When a fellow writer raised a concern that the joke was too obscure, Reiss remembers being very protective: "Someone made some remark about me giving him a joke that nobody was ever going to get, but it stayed in… It was harmless; how funny can the name of a multiplex theatre be?"

My favourite freeze-frame gag appears in "The Wizard of Evergreen Terrace" (1998), in which Homer tries to become an inventor. In one scene, we see him busily scribbling equations on a blackboard. One of the equations relates to the mass of the Higgs boson, another concerns cosmology and the bottom line explores the geometry of doughnuts, but the most interesting equation is the second one, which appears to be a counterexample to Fermat's last theorem.

Although it was only on screen for a moment, this equation immediately caught my eye, because I have written a book on Fermat's last theorem. Homer's scribble sent a shiver down my spine. I was so shocked that I almost snapped my slide rule.

In order to appreciate my reaction, it is necessary to be aware of the colourful history behind Fermat's last theorem. In short, a 17th-century French mathematician called Pierre de Fermat believed that it was impossible to find numbers that fitted a particular equation, and he left a tantalising note proclaiming that he had a proof of this fact, but he never wrote down the proof itself. For more than 300 years, mathematicians desperately tried and failed to rediscover Fermat's proof, which only made his inadvertent challenge even more infamous. Eventually, in the 1980s, Professor Andrew Wiles (now Sir Andrew Wiles) worked in secrecy for seven years to fulfil a childhood dream and build a proof that confirmed that Fermat was right, inasmuch as the following equation has no solution: xn + yn = zn, for n > 2. It is neither necessary to understand the proof nor to examine the equation in detail, except I should stress again that both Wiles and Fermat claimed, indeed proved, that this equation has no solutions, yet Homer's blackboard proves the opposite!

398712 + 436512 = 447212.

Check it for yourself on your phone calculator and you will find that the equation balances! I realise that I have used two exclamation marks in two consecutive sentences, but this is an extraordinary mathematical circumstance. Homer had the audacity and genius to defy two of the greatest mathematicians in history.

Unfortunately, this is a "close but no cigar" moment for Homer. Although the numbers appear to work on a phone calculator with display of perhaps 10 digits, a closer inspection reveals that this is a so-called near miss solution. In other words, there is a minuscule margin of error, with the left side of the equation being 0.000000002% larger than the right side.

Simpsons writer David X Cohen pictured in the Dwight Morrow High School yearbook of 1984. Photograph: Courtesy of David X Cohen

This prank was planted into the episode by David S Cohen, who later changed his name to David X Cohen, in part to reflect his love of algebra. Cohen joined the writing team of The Simpsons soon after completing a masters degree in computer science at the University of California, Berkeley. While working on "The Wizard of Evergreen Terrace", Cohen took a break in order to write a computer program that would scan through values of x, y, z, and n until it found a pseudo-solution to Fermat's equation.

As soon as the episode aired, Cohen patrolled the online message boards to see if anybody had noticed his fake equation. He eventually spotted a posting that read: "I know this would seem to disprove Fermat's last theorem, but I typed it in my calculator and it worked. What in the world is going on here?"

In the late 1990s, Cohen worked with Matt Groening (creator of The Simpsons) to develop Futurama, an animated science fiction series set a thousand years into the future. He recruited some more mathematicians to join Futurama's writing team, including Ken Keeler whose doctoral thesis in applied mathematics was entitled "Map Representations and Optimal Encoding for Image Segmentation".

Not surprisingly, this sister series contained dozens of subtle mathematical references, including an indirect tribute to the great Indian mathematician Ramanujan, objects based on the geometry of the impossible Klein bottle, a freeze-frame gag about the unsolved P v NP problem, a script line about uncountable infinites and much more. Indeed, Futurama can boast the first piece of genuinely innovative and bespoke mathematics to have been created solely for the purposes of a comedy storyline.

Meanwhile, The Simpsons fought back with even more nerdy references, with appearances by the French mathematician Blaise Pascal, numerous jokes about π, a reframing of a classic puzzle by the English polymath Alcuin of York (c735 – 804) and much more.

After spending a week with the writers, it was clear that their fascination with numbers is as strong as ever, and to some extent there was even regret that they had abandoned mathematics in favour of television. In the case of Cohen, his regret at neither proving a deep conjecture nor discovering new geometries is tempered by the feeling that he might have made an indirect contribution to research: "I really would have preferred to live my whole life as a researcher, but I do think that The Simpsons and Futurama make mathematics and science fun, and perhaps that could influence a new generation of people; so, somebody else down the line might achieve what I didn't achieve. I can certainly console myself and sleep at night with thoughts like that."

For more information on Simon Singh's book tour, visit simonsingh.net.

From pancake-flipping to Springfield – the maths prodigies who switched to Homer

When David S Cohen abandoned mathematics to become a comedy writer at the age of 26, he had already co-authored a landmark research paper with Manuel Blum, a winner of the Turing award, known as the Nobel prize of computing. The paper was titled "On the problem of sorting burnt pancakes".

The problem of pancake sorting was raised in 1975 by Jacob E Goodman, a geometer at the City College of New York. Writing under the pseudonym Harry Dweighter (pronounced "harried waiter"), he asked how many flips would be required to arrange a stack of pancakes in their correct order of size, with the widest at the bottom and the smallest at the top.

This seems like a trivial question, but the number of flips depends on the number of pancakes and the order in which they arrive. A flip is defined as inserting a spatula below any pancake and then flipping (or inverting) all the pancakes above the spatula. So far, nobody has been able to work out how many flips would be required to correctly rearrange 20 pancakes in the worst-case scenario. The problem aroused the curiosity of Bill Gates, and it is the subject of his only research paper. Cohen's paper addressed the "burnt" version of the problem, which is slightly trickier, because pancakes must not only be in size order, but also with the burnt side facing down.

When I asked Cohen why a brain suited to researching pancake flipping was also ideal for comedy writing, he suggested that his mathematical training had made him more confident when exploring the unknown: "The process of proving something has some similarity with the process of comedy writing, inasmuch as there's no guarantee you're going to get to your ending. When you're trying to think of a joke out of thin air (that also is on a certain subject or tells a certain story), there's no guarantee that there exists a joke that accomplishes all the things you're trying to do… and is funny. Similarly, if you're trying to prove something mathematically, it's possible that no proof exists. And it's certainly very possible that no proof exists that a person can wrap their mind around. In both cases – finding a joke or proving a theorem – intuition tells you if your time is being invested in a profitable area."

Al Jean, now executive producer, made a similar transition, starting off in the high school yearbook as a proud member of the "mathletics" team and going on to study mathematics at Harvard University. As an undergraduate, Jean was an editor at the Harvard Lampoon, which offered students an opportunity to experiment with comedy writing and performing (the Harvard Lampoon is akin to Cambridge Footlights, giving many students a springboard into a career in comedy). Before joining The Simpsons, Jean worked at The Tonight Show hosted by fellow nerd Johnny Carson. As well as being a respected amateur astronomer, Carson was a debunker of pseudoscience and a committed rationalist.

Are you π-curious?

The Simpsons has created several cameo roles for π, including in the episode "Bye, Bye, Nerdie" (2001). As Lisa waits in the wings to deliver a paper ("Airborne Pheromones and Aggression in Bullies") at the 12th Annual Big Science Thing, Professor Frink is struggling to bring the conference to order. Frustrated and desperate, Frink eventually calls out: "Scientists… Scientists, please! I'm looking for some order. Some order, please, with the eyes forward… and the hands neatly folded… and the paying of attention… π is exactly three!"

Suddenly, the noise stops. Professor Frink's idea worked, because he correctly realised that declaring an exact value for π would stun an audience of geeks into silence. Remember, π is an irrational number, which means that it has an infinite number of decimal places. We often write it as 3.14, but in truth its value is 3.14159265…

Harvard mathematics graduate Al Jean explained that he had introduced the "π is exactly three!" line into the script because he had recently read about an incident that took place in Indiana in 1897, when politicians attempted to legislate an official (and wildly incorrect) value for π.

The Indiana Pi Bill was the brainchild of Edwin J Goodwin, a physician from the town of Solitude in the south-western corner of the state. He had approached the assembly and proposed a bill that focused on his solution to a problem known as "squaring the circle". He seemed oblivious to the fact that this ancient problem had already been proved impossible in 1882. Goodwin's complicated and contradictory "solution" effectively dictated a value for π equal to 3.2. He said that Indiana schools could use his discovery without charge, but that the state and he would share the profits from royalties charged to other schools who wished to adopt a value of 3.2 for π.

Initially, the technical nature of the bill baffled the politicians, who then passed it without any objection. It was then up to the state senate to ratify the bill.

Fortunately, Professor CA Waldo, a mathematician at Indiana's Purdue University, alerted senior politicians to the absurd legislation. This prompted Senator Orrin Hubbell to proclaim: "The Senate might as well try to legislate water to run uphill as to establish mathematical truth by law."

There was a successful motion to indefinitely postpone the passing of the bill, but it still exists in a filing cabinet in the basement of the Indiana statehouse, waiting for a gullible politician to resuscitate it.