Gordon Brown, the British prime minister, has issued a posthumous apology to the mathematician Alan Turing over the "appalling" way he was treated by the British government on account of his sexual preferences.

In a letter to the Daily Telegraph newspaper, Brown, speaking on behalf of the government, said that he is "very proud to say: we're sorry. You deserved so much better."

The apology comes after thousands added their name to an online petition created by computer scientist John Graham Cumming and reported on physicsworld.com last week.

Turing is most famous for helping to crack the codes of the German Enigma machine during the Second World War, which became one of the key aids in the Allied war effort.

He is also considered to be the "father of modern computing" and a key thinker in the field of artificial intelligence.

Rather than being honoured for his work, however, Turing was convicted in 1952 with "gross indecency" for being gay. He was faced with the choice of incarceration or chemical castration through a series of hormone injections.

Turing opted for the latter but just two years later he was found dead, having taken his own life aged just 41.

Referring to the suicide, Brown writes: "While Turing was dealt with under the law of the time, and we can't put the clock back, his treatment was of course utterly unfair, and I am pleased to have the chance to say how deeply sorry I and we all are for what happened to him.

"He truly was one of those individuals we can point to whose unique contribution helped to turn the tide of war. The debt of gratitude he is owed makes it all the more horrifying, therefore, that he was treated so inhumanely."