A young suicide bomber in a school uniform has attacked soldiers during morning exercises at a Pakistani army training camp, killing 31 troops and wounding 42 others, police and the military said.

The attack in the north-west town of Mardan showed that despite years of army operations against their hideouts along Pakistan's border with Afghanistan, Taliban and al Qaida-linked fighters retain the ability to strike back.

It was one of the worst attacks on security forces in recent months.

Senior police official Samad Khan said 31 soldiers died and around 42 were wounded, some critically.

Despite his apparent disguise, the bomber's ability to get his explosives into the facility undetected signalled a failure on the part of the military. Such army areas are usually heavily guarded, though an attack on the same training facility in 2006 killed 35 soldiers.

Troops quickly cordoned off the area and even police had a difficult time getting through.

The army has staged multiple offensives in Pakistan's north west aimed at taking out the Pakistani Taliban in recent years. Its efforts against the group, which is distinct from but linked to the Afghan Taliban, appear to have been largely successful - but violence persists.

The US has encouraged Pakistan to eliminate the Pakistani Taliban in the belief that the long-term stability of the nuclear-armed Muslim nation is critical to global security. Washington also wants Islamabad to take out militants who focus on fighting the US and Nato in Afghanistan but who have bases on Pakistani soil, in particular in the North Waziristan tribal region. But Pakistan has yet to mount an offensive in that area.

The Pakistani Taliban claimed the suicide bomber was a soldier at an army camp in Mardan who volunteered for the attack. Taliban spokesman Ahsanullah Ahsan said the bomber was a soldier who approached them and said "he wanted to sacrifice his life for Islam". "We accepted his offer and told him to target his fellow soldiers in Mardan," said Ahsan.

Former army soldiers have been suspected in attacks in Pakistan, but a suicide bombing by an active duty soldier would be rare, if not unheard of.