Periodical cicadas clearly know how to live. In early summer, they appear in their millions across North America for a frenzy of sex and singing. The sound of them all singing in chorus can be as loud as a jet plane engine or rock concert.

Each cicada is trying to find a mate in one last hurrah before death. "It's like a big party," says Jonathan Larson of the University of Nebraska-Lincoln in Omaha, US.

Their rambunctious final party can blind us to how secretive these insects are. The cicadas spent the vast majority of their lives hidden underground, steadily feeding and growing. Some take 13 years, others 17. They are some of the longest-lived insects in the world, and by far the longest-lived in North America.

Their strange lifestyle has taken decades to understand, and we still don't have the full picture. But we do know that these cicadas live their lives according to mathematics.

All periodical cicadas belong to the same genus, Magicicada. There are three species of 17-year cicada and four species of 13-year cicada. The 17-year cicadas are mostly found in northern US states and 13-year cicadas in south.

Two of the broods died out over the course of the 20th century, so there are now just 15

Together they make up 15 "broods", each on a different life cycle.

The broods are identified by Roman numerals, but the numbering jumps around in a confusing way. For instance there is a brood XIV (14) and a brood XIX (19), but no broods XV (15), XVI (16), XVII (17) or XVIII (18).

That's because in 1898, entomologist Charles Marlatt was under the impression that there were 30 broods, and he named them accordingly. It then turned out that only 17 of his predicted broods existed, but his numbering system has stuck.

What's more, two of the broods died out over the course of the 20th century, so there are now just 15.

These maps show where they can be found.

They are striking insects, with jet-black matte bodies, crimson red googly eyes and intricately veined, orange-flecked wings. Some people find their sheer numbers, and the accompanying noise, disturbing – but in fact they are entirely harmless.

Their parents came out in 2002, the year the United States invaded Afghanistan

Almost every year one of the broods will emerge, before the next generation digs down for another 17 or 13 years. 2015 was a particularly busy year, because two broods emerged.

Brood IV is on a 17-year cycle. Those that came out in 2015 were born in 1998, when Bill Clinton and Tony Blair ruled the western world, Titanicwas still riding high at the box office, and the digital revolution had barely started.

2015 also saw Brood XXIII, a 13-year brood. Their parents came out in 2002, the year the United States invaded Afghanistan and the first Spider-Man movie came out.

This graphic shows when each of the broods emerges.

Once the cicadas appear they live for about a month, if they're not picked off by a voracious predator like a turkey or a mole. It's a long time to develop for just a few weeks of activity.

Like a sword, she slices into the tree and lays her eggs

The males lead particularly short lives. "After they mate they've exhausted their energy reserves so the males die," says Larson. "That terrifies us, because their lives are so short and seemingly pointless."

But the dead males have done their job: they have fertilised females.

Now the females must lay their eggs. To do so, each female must behave a bit like a logger.

"She has this ovipositor on the tip of [her] abdomen and, like a sword, she slices into the tree and lays her eggs," says Larson. This can damage young trees, so people are often advised to protect their trees when the cicadas are out.

From the cicadas' point of view, laying eggs inside trees may prevent them drying out.

"To avoid having your eggs in the dry soil in July and August, you put them in the wet tree instead," says Larson. "They initiate in their development and drop down when things cool off and get a little wetter."

Each clutch numbers on average 500 eggs. As soon as the eggs hatch, the nymphs fall to the ground and start developing.

"They get down into the root zone of the tree, find whatever spot they can, belly-up to the bar and feed on the tree's juices," says Larson.

Imagine you fed your kid nothing but Mountain Dew all his life

There are five stages of development, called instars. It takes years for the nymphs to obtain enough nutrients to pass through them all.

This is partly because their diet is poor. The sugar sap they feed on contains little nitrogen and few nutrients.

"Imagine you fed your kid nothing but Mountain Dew all his life," says Larson. "It would take him 17 years to mature as well."

When the soil reaches 18 °C (65 °F), the cicadas emerge from the soil. They are white and soft when they first come out, but soon darken and harden.

The only insects we can say live as long as periodical cicadas are termite queens

Then the males take to the trees to sing loudly and attract females, who respond by flicking their wings. This extraordinary congregation is a total contrast to the cicadas' dark, sedentary, and solitary lives underground.

The big question is: why do they come out precisely every 17 and 13 years?

Most cicadas go through much shorter life cycles of just 2 to 5 years. "There are other insects that have extended larval life cycles due to poor nutrition, but the only insects we can say live as long as periodical cicadas are termite queens," says Larson.

The key thing about 17 and 13 is that they are both prime numbers: that is, they can only be divided by themselves and 1. That suggests the cicadas gain an advantage by organising their life cycles around prime numbers.

One theory is that it might help them escape predators.

It's a version of a strategy called "predator satiation", which entails overwhelming predators by congregating in huge numbers, too many to eat.

"If you put so many individuals out there that there can't be enough predators to eat all of you, you beat their life cycle," says Larson. It's a "good strategy for maximising reproductive potential."

To regularly catch 17-year cicadas, a predator would also have to be on a 17-year life cycle

However, just emerging in huge numbers might not be enough. Predator populations vary from year to year, and if the cicadas always emerge during years when there are lots of predators about, they would get slaughtered.

That's where the prime numbers come in. A prime-numbered life cycle ensures that it is mathematically unlikely for predators to be on the same cycle.

To regularly catch 17-year cicadas, a predator would also have to be on a 17-year life cycle. Anything shorter, and they would miss the cicadas most years.

For comparison, if the cicadas were on a 15-year life cycle, their emergence would coincide with peaks of predators on 3-year and 5-year cycles.

Alternatively, the cicadas' long life cycles could be a response to the environment in which they evolved.

The clock is undoubtedly a molecular clock

They first appeared during the Pleistocene period, when North America was repeatedly smothered under sheets of ice. So it's been suggested that they may have remained underground for longer to avoid the colder climate.

Even if that's true, it doesn't explain the really weird thing about periodical cicadas. These insects can count, and unlike most animals they can count to quite large numbers. How do they know when 17 or 13 years have passed?

Most animals have an internal clock and that will surely be part of the answer. "The clock is undoubtedly a molecular clock," says Chris Simon of the University of Connecticut in Storrs, US.

But that's not enough.

"You've got to have some way of calibrating it, [of] knowing when a year's gone by," says Simon. "They do that by monitoring some aspect of the environment, and we think it's the trees since they're feeding on the roots."

Fluid flows through the roots of trees, and the flow changes throughout the year. The cicadas could well be monitoring this annual cycle, says Gene Kritsky of Mount St. Joseph University in Cincinnati, Ohio. "They can tell the increase of fluid through the year."

Beyond that, they may count in a particular way. Although most periodical cicadas stick to their 17- and 13-year patterns, some have been known to come out early, or late. They are called stragglers.

The key thing is that they are often 4 years late or early. "We so often see these 4-year-early or 4-year-late emergences," says Simon. "Some people have even seen 4-year-early 13-year cicadas."

This early emergence could lead to the formation of an entirely new brood

That suggests the number 4 is significant.

In the 1990s, while teaching an ecology course, Kritsky asked his students to dig up some cicadas from Brood X while they were still developing. The cicadas were bigger than they should have been at that stage in their cycle, so Kritsky predicted that they might come out early, in 2000 rather than 2004.

They did. "It was the first time anyone predicted a 4-year acceleration that actually took place," says Kritsky. This early emergence could lead to the formation of an entirely new brood, if the cicadas born in 2000 emerge in 2017 in enough numbers.

"We think they're counting in groups of four," says Simon. That may be because each instar period lasts four years on average.

Simon is now working with scientists in Japan to sequence the genome of periodical cicadas, in the hope that their DNA will offer some answers.

Kritsky says looking at the cicadas' genes and biochemistry is the right way to go. "What is the periodicity gene? Is there a single gene? What are the biochemical processes? We're making progress in our understanding of the domino effect, how one thing triggers the next and the next."

While scientists try and work out the strange mystery of their life cycle, the periodical cicadas are vulnerable.

Two broods have already died out: Brood XI and Brood XXI. Their deaths have been attributed to various factors, including industrialisation and use of the insecticide DDT. Brood VII may be the next to go: its numbers seem to be dwindling.

Anything that can flood them out will knock their populations

Climate change may be a factor. Over the last few years, Kritsky has noticed that they are emerging over a week earlier: instead of popping up after 21 May, broods are now appearing as early as 10 May.

"Without any doubt, we are seeing a continent-wide increase of temperatures in North America," says Kritsky. "We're certainly seeing an effect."

It's not clear if emerging earlier is bad for the cicadas, or simply a sign that they are adapting to the warmer climate. But Larson suspects that another consequence of climate change is hurting the cicadas.

In 2015 he was studying cicadas in Nebraska, and didn't see the emergence that he expected. He thinks that may be because the cicadas were flooded.

Periodical cicadas have to mate and lay eggs in trees, so no trees means no periodical cicadas

"They live along the river corridors because that's where all the good trees are, so anything that can flood them out will knock their populations," says Larson.

That implicates climate change. A warmer climate brings more extreme weather, and for some places that means more intense rain storms that can cause floods. "These extreme weather patterns are definitely going to take their toll," says Larson

Deforestation is also a factor.

Periodical cicadas have to mate and lay eggs in trees, so no trees means no periodical cicadas. Yet in many places trees have been cut down to make room for farms, fragmenting and destroying the cicadas' habitat.

"The big surprise for me this year was the impact of fragmentation, how scattered the emergence is," says Kritsky. "It's much more patchy. That's kinda sad."

For now, you can still see periodical cicadas most summers, and the next few years should be particularly rich.

"We're coming into the big cycle," says Kritsky. "You've got a good six or seven years. Next year is Brood IV in eastern Ohio, the following year is V in North Carolina."

2021 will see the emergence of Brood X, which has the largest geographical range. Kritsky describes it as "the mother of them all".

It is also the brood immortalised by Bob Dylan in his song "Day of the Locusts". Dylan heard Brood X singing their "sweet melody" while collecting an honorary degree from Princeton University in New Jersey in 1970.

"That's the one you want to go to," says Kritsky.