T-SQL Query | [ The Perfect Number Puzzle ]

What is a Perfect Number ?
In number theory, a perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself (also known as its aliquot sum).

What is the logic to find a given number is a perfect number ? For example 6 is perfect Number which is divisible by 3,2,1 and their sum is 6, so 6 is a perfect number.

List of Perfect Numbers – http://en.wikipedia.org/wiki/List_of_perfect_numbers

Puzzle Statement

We will be given an integer input and we have find out whether the given number is a Perfect Number or not.

Sample Input

Any of the below numbers

6

28

496

14

25..etc

Expected output

In case of 496 you should get below output

 Nums 496  is a Perfect Number

UPDATE – 24-Apr-2015 – Solution 1

 ``` -- DECLARE @t AS INT = 496 DECLARE @Cnt AS INT = 1 CREATE TABLE #Prime ( Val INT ) WHILE ( @Cnt <= @t/2 ) BEGIN IF @t% @cnt = 0 BEGIN INSERT INTO #Prime VALUES (@Cnt) END SET @Cnt = @Cnt + 1 END SELECT CASE WHEN SUM(Val) = @t THEN CONCAT (@t,' is a Perfect Number') ELSE CONCAT (@t,' is NOT a Perfect Number') END Nums FROM #Prime DROP TABLE #Prime -- ```

Add a comment if you have any other solution in mind. We all need to learn.

Keep Learning

http://MSBISkills.com