C# Program to print perfect numbers from 1 to N

In this C# program, we will take input from the user and print perfect numbers between 1 and the number input by the user. A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. For instance, 6 has divisors 1, 2 and 3, and 1 + 2 + 3 = 6, so 6 is a perfect number.

C# Program to print perfect numbers from 1 to N Code:

private static void Main(string[] args)
        {
            int n, i, sum;
            Console.WriteLine("Enter the nth No");
            int nthNo = Int32.Parse(Console.ReadLine());
            Console.Write("Perfect numbers between 1 and {0} are: ", nthNo);
            for (n = 1; n <= nthNo; n++)
            {
                i = 1;
                sum = 0;
                while (i < n)
                {
                    if (n % i == 0)
                        sum = sum + i;
                    i++;
                }
                if (sum == n)
                    Console.Write("{0} ", n);
            }
            Console.Write("\n");

            Console.ReadLine();
        }

C# Program to print perfect numbers from 1 to N Output:

C#-Program-to-print-perfect-numbers-from-1-to-N

 
Best quality Asp .Net Ajax Control Toolkit tutorials.

Give your valuable comments.

Name
Email
Comment
8 + 5 =
 

About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2024 CodingFusion
50+ C# Programs for beginners to practice