0

I am trying to find a perfect number between two given numbers for example 1 and 50. Unfortunately my code prints 1 and 24 as perfect numbers.

Can someone please correct this code and explain what they have done?

I am new to coding so please don't tell me about lists and stuff, I am here to seek your help to know where I am going wrong and how I can improve it. I shall be grateful to you if you will correct this code.

class Program
{
    static void Main(string[] args)
    {
        int n2 = int.Parse(Console.ReadLine());
        int n3 = int.Parse(Console.ReadLine());

        //int sum;            

        for (int i = n2; i < n3; i++)
        {
            int sum = 0;

            for (int j = 1; j <= i; j++)
            {
                if (i % j == 0 )
                    sum = sum + j;

                //Console.WriteLine(j);
                if (sum == i )
                {
                    Console.WriteLine("the sum is " + i);
                }
            }                                                            
        }

        Console.ReadLine();
    }                                           
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Van Bever
  • 19
  • 5
  • 2
    Before we can help, you need to **define** what you mean by a "perfect number". Explain to us, in plain English, what the code is supposed to accomplish. What is the expected output? Why are 1 and 24 not correct answers? – Idle_Mind Dec 17 '19 at 00:56
  • And if you are coming here for help on your code, you should listen to suggestions whether they include lists or dictionaries. – Jawad Dec 17 '19 at 01:00
  • What is the definition of the perfect number? – Jawad Dec 17 '19 at 01:01

1 Answers1

2

You need to begin by defining what a perfect number is. A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. Let examine your code

for (int j = 1; j <= i; j++)

According to your inner loop, you are NOT excluding the number itself. This needs to be changed to

for (int j = 1; j < i; j++).

The second issue with the code is that you are validating the sum way too early.

if (sum == i )
{
    Console.WriteLine("the sum is " + i);
}

The sum, at this point, could include only a part of positive divisors. You are yet to look though the entire list of divisors yet. So the validation part has to lie outside the inner loop. For example,

int n2 = int.Parse(Console.ReadLine());
int n3 = int.Parse(Console.ReadLine());

for (int i = n2; i < n3; i++)
{
    int sum = 0;
    for (int j = 1; j < i; j++)  // you need to exclude the number itself. So use Loop condition j <i, instead of j <=i
    {
        if (i % j == 0 )
        {
            sum = sum + j;

        }
    }      
    if (sum == i )  // Validate the sum with the number only after calculating sum of all divisors.
                {
        Console.WriteLine("the sum is " + i);
    }
}
Anu Viswan
  • 17,797
  • 2
  • 22
  • 51