The Prime Minister last night said Alan Turing, who took his own life in 1954, had been treated “inhumanely” and paid tribute to his work cracking the German Enigma codes.

Writing on the Downing Street website after thousands signed a petition calling for an apology, Mr Brown said 2009 had been a year for “deep reflection” and a chance for Britain “to commemorate the profound debts we owe to those who came before” because of the 65th anniversary of the Normandy landings and the 70th anniversary of the UK’s commitment to fight fascism.

He went on: “I am both pleased and proud that, thanks to a coalition of computer scientists, historians and LGBT activists, we have this year a chance to mark and celebrate another contribution to Britain’s fight against the darkness of dictatorship; that of code-breaker Alan Turing.”

Describing Mr Turing as a “quite brilliant mathematician”, the Prime Minister said: “It is no exaggeration to say that, without his outstanding contribution, the history of World War Two could well have been very different. 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. In 1952, he was convicted of ‘gross indecency’ - in effect, tried for being gay. His sentence - and he was faced with the miserable choice of this or prison - was chemical castration by a series of injections of female hormones. He took his own life just two years later.

“Thousands of people have come together to demand justice for Alan Turing and recognition of the appalling way he was treated.

“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.”

Mr Brown said thousands of other gay men convicted under laws prohibiting homosexual relationships had been treated “terribly”.

And praising Mr Turing’s code-breaking work for its role in helping defeat fascism. The Prime Minister added: “On behalf of the British government, and all those who live freely thanks to Alan’s work I am very proud to say: we’re sorry, you deserved so much better.”

Alan Turing