Reputation: 19
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();
}
}
Upvotes: 0
Views: 224
Reputation: 18153
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);
}
}
Upvotes: 2