At the launch of a government technology initiative, Lee Hsien Loong said he had written the "pretty basic" computer program a few years ago.
On Facebook, he revealed he had written it in the C++ programming language, first widely used in the 1980s.
It has led to thousands of responses praising him for knowing how to code.
Mr Lee, who graduated from Cambridge University with a first-class degree in mathematics and a diploma in computer science, asked readers to tell him "if they found any bugs".
Many of the hundreds of comments the post has attracted have been from people from countries outside Singapore, admiring the Mr Lee's skills, with some lamenting the technical abilities of their own leaders.
Singapore's population has one of the highest levels of computer ownership in the world.
The government has been keen to present the island as a test bed for new technology innovations.
Mr Lee said it was imperative Singapore stayed ahead of the game when it came to technology and programming.
Singapore's prime minister has revealed his computer programming skills by publishing code he wrote to solve Sudoku puzzles, on his Facebook page.