This question already has answers here:
Best way to find all factors of a given number
(14 answers)
Closed 4 years ago.
I'm trying to get all the factors of a number provided by a user and after a button click displaying all the factors on a MessageBox.
This is what my code code taken from Getting Factors of a Number answer by Mark Byers looks like, I thought I was pretty close, but I'm displaying the number of factors not the actual factor numbers.
For example if the user types in 10 and uses a button click, the MessageBox displays the number 4, but i'm wanting it to display the actual factors of 10 which should be 1,2,5,10.
*how can I display the factors?
public int Divisors(int fact)
{
int number = int.Parse(textBox2.Text);
int factorCount = 0;
int sqrt = (int)Math.Ceiling(Math.Sqrt(number));
for (int i = 1; i < sqrt; i++)
{
if (number % i == 0)
{
factorCount += 2; // We found a pair of factors.
}
}
// Check if our number is an exact square.
if (sqrt * sqrt == number)
{
factorCount++;
}
return factorCount;
}
private void ShowallButton_Click(object sender, EventArgs e)
{
int input = int.Parse(textBox2.Text);
double output = Divisors(input);
MessageBox.Show(+output + "");
}
public List<int> Divisors(int fact)
{
List<int> factors = new List<int>();
int number = int.Parse(textBox2.Text);
int factorCount = 0;
int sqrt = (int)Math.Ceiling(Math.Sqrt(number));
for (int i = 1; i < sqrt; i++)
{
if (number % i == 0)
{
factors.Add(i);
factorCount += 2; // We found a pair of factors.
}
}
// Check if our number is an exact square.
if (sqrt * sqrt == number)
{
factorCount++;
}
// return factorCount;
return factors;
}
private void ShowallButton_Click(object sender, EventArgs e)
{
int input = int.Parse(textBox2.Text);
List<int> factors = Divisors(input);
string message = $"The Divisors are {string.Join(",", factors)}";
MessageBox.Show(message);
}
This is not very close at all.
Lets look at the factorisation first
% Operator (C# Reference)
The remainder operator % computes the remainder after dividing its
first operand by its second operand.
public static void Divisors(int number )
{
for (var x = 1; x <= number; x++)
if (number % x == 0) // no remainder it must be a factor
Console.WriteLine(x);
}
usage
Divisors(10);
Output
1
2
5
10
Now Lets return an Enumerable using yield
public static IEnumerable<int> Divisors(int number )
{
for (var x = 1; x <= number; x++)
if (number % x == 0) // no remainder it must be a factor
yield return x;
}
Usage
var results = Divisors(10);
Console.WriteLine(string.Join(", ", results));
Output
1, 2, 5, 10
Additional resources
yield (C# Reference)
When you use the yield contextual keyword in a statement, you indicate
that the method, operator, or get accessor in which it appears is an
iterator. Using yield to define an iterator removes the need for an
explicit extra class (the class that holds the state for an
enumeration, see IEnumerator for an example) when you implement the
IEnumerable and IEnumerator pattern for a custom collection type.
String.Join Method
Concatenates the elements of a specified array or the members of a
collection, using the specified separator between each element or
member.
private void ShowallButton_Click(object sender, EventArgs e)
{
var input = int.Parse(textBox2.Text);
var output = Divisors(input);
var message = string.Join(Environment.NewLine, output);
MessageBox.Show(message);
}
public List<int> Divisors(int number)
{
var factors = new List<int>();
for (var i = 1; i <= number; i++)
{
if (number % i == 0)
{
factors.Add(i);
}
}
return factors;
}
Related
I am writing an application where each multiple of 4 and 6 is added to a total variable named answer.
I am receiving this error, "The name 'sum' does not exist in the current context" It is occurring at Console.WriteLine(sum);.
class Program
{
static void Main(string[] args, int answer)
{
//Local Variables
int i;
int total = 0;
//Initialize Console
Console.WriteLine("Enter a number to begin");
string input = Console.ReadLine();
//Create integer from string input
int number = int.Parse(input);
//For Loop Looking for Multiples
for (i = 0; i < number; i++)
{
if (i % 4 == 0 || i % 6 == 0)
{
int sum;
sum = total + i;
}
Console.WriteLine(sum);
}
}
}
You Have To Declare The Variable sum out of if statement because this variable known only in if statement when the code get out of if statement the program doesn't know sum...The program know sum only in if statement
Each local variable exists within its scope {...} where it's declared:
if (i % 4 == 0 || i % 6 == 0)
{ // <- Scope of sum begins here
int sum;
sum = total + i;
} // <- Scope of sum ends here
Console.WriteLine(sum); // <- sum doesn't exists here (out of scope)
Let's move sum declaration out of the if and loop (in order to declare sum in a wider scope):
//DONE: , int answer dropped
static void Main(string[] args)
{ // <- now sum scope begins here
...
int sum = 0;
for (i = 0; i < number; i++)
{
if (i % 4 == 0 || i % 6 == 0)
{
//DONE: you probably want to add i to sum, not to total
sum = sum + i;
}
Console.WriteLine(sum);
}
} // <- sum scope ends here
In this case, you face such error because sum is declared inside if scope and it is not visible outside. You should move sum variable declaration out of if scope to make it visible for Console.WriteLine(...) method.
But as you mentioned, you just need to store a total number. So you don't even need sum variable here because you have total variable.
So let's rewrite this code like that:
class Program
{
static void Main(string[] args, int answer)
{
//Local Variables
int i;
int total = 0;
//Initialize Console
Console.WriteLine("Enter a number to begin");
string input = Console.ReadLine();
//Create integer from string input
int number = int.Parse(input);
//For Loop Looking for Multiples
for (i = 0; i < number; i++)
{
if (i % 4 == 0 || i % 6 == 0)
{
total += i;
}
Console.WriteLine(total);
}
}
}
I've written this code with Visual studio c# WindowsForms but it doesn't work as it should.
On my Form1:
private void btnVisualizzaPrezzoMin_Click(object sender, EventArgs e)
{
listView1.Items.Clear();
int i = 0;
while (i < num)
{
if (eleMutui[i].Durata <= int.Parse(txtDurata2.Text) && eleMutui[i].Durata >= int.Parse(txtDurata1.Text))
{
int Min = Funzioni.ImportoMin(eleMutui, num);
ListViewItem Nuovariga = default(ListViewItem);
Nuovariga = new ListViewItem(new string[] {
eleMutui[Min].Codice.ToString(),
eleMutui[Min].Nome,
eleMutui[Min].Provincia,
eleMutui[Min].DataPartenza.ToString(),
eleMutui[Min].Importo.ToString(),
eleMutui[Min].Durata.ToString()
});
listView1.Items.Add(Nuovariga);
}
i++;
}
And the Minimum funcion is:
public static int ImportoMin(Mutui[] ele, int n)
{
int x = 0;
decimal MinimoImporto = default(int);
while (x < n)
{
if (ele[x].Importo < MinimoImporto)
{
MinimoImporto = ele[x].Importo;
}
x++;
}
return decimal.ToInt32(MinimoImporto);
}
Can you help me? I have to do: given by the user a duration interval (ex. between 60 and 120 months), display all the data of the
loan of a lower amount that has a duration in the indicated range.
Thank you!!
It's hard to understand why you use n in ImportoMin(), when you are basically just looping though the []. (That is if n is supposed to be the length of the [], but I don't see where num is declared.)
To continue with your format, you can do something like this:
public static int ImportoMin(Mutui[] ele)
{
decimal MinimoImporto = int.MaxValue;
for(int x = 0; x < ele.length; x++)
{
if (ele[x].Importo < MinimoImporto)
{
MinimoImporto = ele[x].Importo;
}
}
return decimal.ToInt32(MinimoImporto);
}
The issue with your method is that you initialize the min value to zero. Meaning that if all the values in the array are greater than zero then it's going to return zero instead of the actual min. The second issue is that you seem to want the index of the minimum value but you don't keep track of the index and instead return either 0 or the actual min in the array when it's negative (if that's possible). One option is to use MoreLinq's MinBy instead.
var itemWithMinImporto = eleMutui.MinBy(x => x.Importto);
Or you can do that with Linq
var itemWithMinImporto = eleMutui.OrderBy(x=>x.Importto).FirstOrDefault();
Or you can find the index with a normal for loop
int minIndex = -1;
decimal minValue = decimal.MaxValue;
for(int i = 0; i < eleMutui.Length; i++)
{
if(item[i].Importto < minValue)
{
minValue = item[i].Importto;
minIndex = i;
}
}
return minIndex;
Note that it's not clear if n is the actual length of the array or not. If not the above code can be altered to take that into account by using Take(n) for the MoreLinq and Linq solutions or just doing i < n in the for loop.
In your function ImportoMin, instead of using a while loop, you should probably do a for loop instead.
public static int ImportoMin(Mutui[] ele)
{
// I'd return -1 or something to indicate something is wrong
if(ele.Count == 0) return -1;
decimal MinimoImporto = int.MaxValue;
for(int i = 1; i < ele.Length; i++)
{
if( ele[i].Importo < MinimoImporto)
MinimoImporto = ele[i].Importo;
}
return MinimoImporto;
}
In your funciton, you initialize your min to be zero and unless everything else is negative, it will return zero every time.
Edit: This function will return the minimum value in the array, however you can refer to juharr's answer if you're looking for the index.
I try to write program that check the ratio between odd and even
digits in a given number. I've had some problems with this code:
static void Main(string[] args)
{
int countEven = 0 ;
int countOdd = 0 ;
Console.WriteLine("insert a number");
int num = int.Parse(Console.ReadLine());
int length = num.GetLength;
for (int i = 0;i<length ; i++)
{
if((num/10)%2) == 0)
int countEven++;
}
}
any ideas?
The problem is that int does not have a length, only the string representation of it has one.As an alternative to m.rogalski answer, you can treat the input as a string to get all the digits one by one. Once you have a digit, then parsing it to int and checking if it is even or odd is trivial.Would be something like this:
int countEven = 0;
int countOdd = 0;
Console.WriteLine("insert a number");
string inputString = Console.ReadLine();
for (int i = 0; i < inputString.Length; i++)
{
if ((int.Parse(inputString[i].ToString()) % 2) == 0)
countEven++;
else
countOdd++;
}
Linq approach
Console.WriteLine("insert a number");
string num = Console.ReadLine(); // check for valid number here?
int countEven = num.Select(x => x - '0').Count(x => x % 2 == 0);
int countOdd = num.Select(x => x - '0').Count(x => x % 2 != 0);
Let's assume your input is : 123456
Now all you have to do is to get the modulo from the division by ten : int m = num % 10;
After that just check if bool isEven = m % 2 == 0;
On the end you have to just divide your input number by 10 and repeat the whole process till the end of numbers.
int a = 123456, oddCounter = 0, evenCounter = 0;
do
{
int m = a % 10;
switch(m % 2)
{
case 0:
evenCounter++;
break;
default: // case 1:
oddCounter++;
break;
}
//bool isEven = m % 2 == 0;
}while( ( a /= 10 ) != 0 );
Online example
Made a small change to your code and it works perfectly
int countEven = 0;
int countOdd = 0;
Console.WriteLine( "insert a number" );
char[] nums = Console.ReadLine().ToCharArray();
for ( int i = 0; i < nums.Length; i++ )
{
if ( int.Parse( nums[i].ToString() ) % 2 == 0 )
{
countEven++;
}
else
{
countOdd++;
}
}
Console.WriteLine($"{countEven} even numbers \n{countOdd} odd numbers");
Console.ReadKey();
What I do is get each number as a a character in an array char[] and I loop through this array and check if its even or not.
If the Input number is a 32-bit integer (user pick the length of the number)
if asked:
The number of even digits in the input number
Product of odd digits in the input number
The sum of all digits of the input number
private void button1_Click(object sender, EventArgs e) {
int num = ConvertToInt32(textBox1.Text);
int len_num = textBox1.Text.Length;
int[] arn = new int[len_num];
int cEv = 0; pOd = 0; s = 0;
for (int i = len_num-1; i >= 0; i--) { // loop until integer length is got down to 1
arn[i] = broj % 10; //using the mod we put the last digit into a declared array
if (arn[i] % 2 == 0) { // then check, is current digit even or odd
cEv++; // count even digits
} else { // or odd
if (pOd == 0) pOd++; // avoid product with zero
pOd *= arn [i]; // and multiply odd digits
}
num /= 10; // we divide by 10 until it's length is get to 1(len_num-1)
s += arn [i]; // sum of all digits
}
// and at last showing it in labels...
label2.Text = "a) The even digits count is: " + Convert.ToString(cEv);
label3.Text = "b) The product of odd digits is: " + Convert.ToString(pOd);
label4.Text = "c) The sum of all digits in this number is: " + Convert.ToString(s);
}
All we need in the interface is the textbox for entering the number, the button for the tasks, and labels to show obtained results. Of course, we have the same result if we use a classic form for the for loop like for (int i = 0; and <= len_num-1; i++) - because the essence is to count the even or odd digits rather than the sequence of the digits entry into the array
static void Main(string args[]) {
WriteLine("Please enter a number...");
var num = ReadLine();
// Check if input is a number
if (!long.TryParse(num, out _)) {
WriteLine("NaN!");
return;
}
var evenChars = 0;
var oddChars = 0;
// Convert string to char array, rid of any non-numeric characters (e.g.: -)
num.ToCharArray().Where(c => char.IsDigit(c)).ToList().ForEach(c => {
byte.TryParse(c.ToString(), out var b);
if (b % 2 == 0)
evenChars++;
else
oddChars++;
});
// Continue with code
}
EDIT:
You could also do this with a helper (local) function within the method body:
static void Main(string args[]) {
WriteLine("Please enter a number...");
var num = ReadLine();
// Check if input is a number
if (!long.TryParse(num, out _)) {
WriteLine("NaN!");
return;
}
var evenChars = 0;
var oddChars = 0;
// Convert string to char array, rid of any non-numeric characters (e.g.: -)
num.ToCharArray().Where(c => char.IsDigit(c)).ToList().ForEach(c => {
byte.TryParse(c.ToString(), out var b);
if (b % 2 == 0)
evenChars++;
else
oddChars++;
// Alternative method:
IsEven(b) ? evenChars++ : oddChars++;
});
// Continue with code
bool IsEven(byte b) => b % 2 == 0;
}
Why am I using a byte?
Dealing with numbers, it is ideal to use datatypes that don't take up as much RAM.
Granted, not as much an issue nowadays with multiple 100s of gigabytes possible, however, it is something not to be neglected.
An integer takes up 32 bits (4 bytes) of RAM, whereas a byte takes up a single byte (8 bits).
Imagine you're processing 1 mio. single-digit numbers, and assigning them each to integers. You're using 4 MiB of RAM, whereas the byte would only use up 1 MiB for 1 mio. numbers.
And seeming as a single-digit number (as is used in this case) can only go up to 9 (0-9), you're wasting a potential of 28 bits of memory (2^28) - whereas a byte can only go up to 255 (0-255), you're only wasting a measly four bits (2^4) of memory.
For instance, if the input is set to 1234, the program will return 11213141 because digit 1 occurs once, digit 2 occurs once ... so on and so forth.
Another example: 142225 => 11234151
My program works fine with small input but if the input has 10 digits or more, the result would make no sense. Please help.
class Example
{
// Get sorted(ascending) list for each digit in num
public static List<int> GetList(long num)
{
List<int> listOfInts = new List<int>();
while (num > 0)
{
int remainder = (int) num % 10;
listOfInts.Add(remainder);
num = num / 10;
}
listOfInts.Sort();
return listOfInts;
}
// Get minimum digit in the list
public static int getMinimumInt(List<int> l)
{
int min = 10;
foreach (int s in l)
{
if (s <= min)
{
min = s;
}
}
return min;
}
// Get count of the minimum digit specified
public static int getCount(int i,List<int> l)
{
int count = 0;
foreach (int s in l)
{
if (s == i)
{
count++;
}
}
return count;
}
public static void Main()
{
long input = 1234567891020; // Arbituary input
// initialize
List<int> outputList=new List<int>(); // List that would be eventually outputted
List<int> listOfInt = new List<int>();
listOfInt = GetList(input);
//Loop end till no element left in listOfInt
while ((listOfInt.ToArray()).Length!=0)
{
int item = getMinimumInt(listOfInt);
int count = getCount(item, listOfInt);
outputList.Add(item); // Add the item to be counted
outputList.Add(count); // Add count of the item
listOfInt.RemoveRange(0, count); // Remove digits that have been counted
}
// Output the list
foreach (int i in outputList)
{
Console.Write(i);
}
Console.WriteLine();
Console.ReadLine();
}
}
}
In your GetList() function, you are casting your 10+ digit long to an integer:
int remainder = (int) num % 10;
Attempting to place a 10+ digit number into an int means you are running up against the highest value of 32-bit integers, which is 2,147,483,647. That would explain why your results seem strange.
Use a long instead. If that isn't enough you can try System.Numerics.BigInteger, which will allow you to add more digits to it until you run out of memory.
You can use this LINQ approach, it doesn't care about numbers, just chars:
string output = String.Concat(input
.GroupBy(c => c)
.Select(g => String.Format("{0}{1}", g.Key, g.Count())));
If you want the result as long use long.TryParse(output, out longvariable).
int sourceVal = 12341231;
string sourceStr = sourceVal.ToString();
List<char> uniqueChars = null;
#if LINQ
uniqueChars = sourceStr.ToCharArray().Distinct().ToList();
#else
uniqueChars = new List<char>();
foreach (char c in sourceStr)
if (!uniqueChars.Contains(c))
uniqueChars.Add(c);
#endif
string result = "";
foreach (var wantedChar in uniqueChars)
#if LINQ
result += wantedChar.ToString() + (sourceStr.Count(f => f == wantedChar)).ToString();
#else
result += wantedChar.ToString() + (sourceStr.Split(wantedChar).Length - 1).ToString();
#endif
Console.WriteLine("Result = " + result);
This was my code to keep it as similar to yours. If you want to limit the count, use a modulus on the end (% 10) to keep the count to a single digit.
Having now seen the other Linq answer, I think that is a lot neater. Given that your maximum answer would be something like 192,939,495,969,798,999 if sorted in character order ascending, you would need a long not an int to store that.
Just change
int remainder = (int) num % 10;
to
int remainder = (int)(num % 10);
The first one is casting num to int then doing the mod 10. This will result in overflow when num is larger than int.MaxValue, typically a negative number. The second does the mod 10 first then the cast, which is safe as the mod will result in a value that can easily fit into an int.
can you help me with the following exercise pls? (it's not homework, just an exercise in the book I'm using.)
"An integer is said to be a perfect number if its factors, including one (but not the number itself), sum to the number. For example, 6 is a perfect number, because 6 = 1 + 2 + 3. Write method Perfect that determines whether parameter value is a perfect number. Use this method in an app that determines and displays all the perfect numbers between 2 and 1000. Display the factors of each perfect number to confirm that the number is indeed perfect."
so here's what i got so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Perfect_Numbers2
{
class Program
{
static bool IsItPerfect(int value)
{
int x = 0;
int counter = 0;
bool IsPerfect = false;
List<int> myList = new List<int>();
for (int i = value; i <= value; i++)
{
for (int j = 1; j < value; j++)
{
// if the remainder of i divided by j is zero, then j is a factor of i
if (i%j == 0) {
myList[counter] = j; //add j to the list
counter++;
}
for (int k = 0; k < counter; k++)
{
// add all the numbers in the list together, then
x = myList[k] + myList[k + 1];
}
// test if the sum of the factors equals the number itself (in which case it is a perfect number)
if (x == i) {
IsPerfect = true;
}
}
Console.WriteLine(i);
}
return IsPerfect;
}
static void Main(string[] args)
{
bool IsItAPerfectNum = false;
for (int i = 2; i < 1001; i++)
{
IsItAPerfectNum = IsItPerfect(i);
}
}
}
}
how would you do it? is my code fixable? how would you fix it? thanks!
im getting an error at line myList[counter] = j; (index was out of range) and besides it's not displaying the perfect numbers like it's supposed to....
EDIT = I made some changes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Perfect_Numbers2
{
class Program
{
static bool IsItPerfect(int value)
{
int x = 0;
int counter = 0;
bool IsPerfect = false;
List<int> myList = new List<int>();
for (int i = value; i <= value; i++)
{
for (int j = 1; j < i; j++)
{
if (i%j == 0) // if the remainder of i divided by j is zero, then j is a factor of i
{
myList.Add(j); //add j to the list
}
x = myList.Sum();
if (x == i) // test if the sum of the factors equals the number itself (in which case it is a perfect number)
{
IsPerfect = true;
}
}
Console.WriteLine(i);
}
return IsPerfect;
}
static void Main(string[] args)
{
bool IsItAPerfectNum = false;
for (int i = 2; i < 1001; i++)
{
IsItAPerfectNum = IsItPerfect(i);
Console.WriteLine(IsItAPerfectNum);
Console.ReadKey(true);
}
}
}
}
now i can cycle through all the numbers until 1000 and it displays if it's perfect or not (true or false) [which isn't what the exercise called for, but it's a step in the right direction (the exercise says that it should display only the perfect numbers)].
In any case, what's strange is that it says true at number 24, which isn't a perfect number.... http://en.wikipedia.org/wiki/Perfect_numbers#Examples
why is 24 different?
thanks very much
can you help me with the following exercise please?
Yes. Rather than showing you where your error is, I'll teach you how to find your error. Even better, the same technique will lower the chances of you causing the error in the first place.
The key here is to break the problem down into small parts where each small part can be tested independently. You have already started to do this! You have two methods: Main and IsItPerfect. You should have at least three more methods. The methods you should have are:
IsDivisor -- takes two integers, returns true if the first divides the second.
GetAllDivisors -- takes an integer, returns a list of all the divisors
Sum -- takes a list of integers, returns the sum
Your method IsPerfect should be calling GetAllDivisors and Sum and comparing the sum to the original number, and that's all it should be doing. Your method GetAllDivisors should be calling IsDivisor, and so on.
You can't find the bug easily because your method is doing too much. If you're not getting the correct result out and you have four methods instead of one then you can test each method independently to make sure that it works, or fix it if it does not.
Your first for loop will be executed exactly once.
for (int i = value; i <= value; i++)
For example for value = 6
for (int i = 6; i <= 6; i++)
Some help with the 24 issue you are having: 24 is returning true as you are actually checking if it is perfect on every additional factor. So 24 gets flipped to true here:
Factors of 24 | Total so far
1 1
2 3
3 6
4 10
6 16
8 24 <-- returns true
12 36 <-- should be false, but flag is never reset
I have just now completed the same exercise which is from a really great book called visual c# 2012 by Mr Deitel.
The way i started to tackle is, i started off with figuring out how to work out the factorials of numbers and then slowly kept building on from there.
Since you are following the same book, i would suggest you not to use things that are not covered up to that chapters exercise, like list collections which you have used, As this will make the exercise unnecessarily difficult. and negates the learning methodology set out by of the author.
here is my code which i hope can help you in some way.
class Program
{
static int factorTotal = 1;
static void Main(string[] args)
{
int count = 1;
while (count <= 10000)
{
bool isPerfect = IsPerfectNumber(count);
if (isPerfect && (factorTotal >1))
{
Console.WriteLine("Is Perfect: {0}", factorTotal);
}
factorTotal = 1;
count++;
}
} // end main
static bool IsPerfectNumber(int n)
{
int temp;
int counter = 2;
bool IsPerfect = false;
while (counter <= (n - 1))
{
temp = n % counter;
if (temp == 0) // if true than factor found
{
factorTotal = factorTotal + counter;
}
counter++;
}
if ((factorTotal) == n)
IsPerfect = true;
else
IsPerfect = false;
return IsPerfect;
}
}//end class
under the Main method of you console application copy and paste below code.
I explained few things at the end of the code...
=====================================================================
{
Console.WriteLine("perfect numbers/n");
Console.Write("Enter upper limit: ");
int iUpperLimit = int.Parse(Console.ReadLine());
string sNumbers = "";
List<int> lstFactor = new List<int>();
for(int i = 1;i<=iUpperLimit;i++)
{
for(int k = 1;k<i;k++)
{
if (i % k == 0)
{
lstFactor.Add(k); //this collect all factors
}
if (k == i-1)
{
if (lstFactor.Sum() == i) //explain1
{
sNumbers += " " + i;
lstFactor.Clear(); //explain2
break;
}
else
{
lstFactor.Clear(); //explain2
}
}
}
}
Console.WriteLine("\nperfect numbers are: " + sNumbers);
Console.ReadKey();
}
}
=======================================================================
note that i is a number that we test and k is its factors.
explain1 => we add all factors collected and check if they are equal to i (we simply check if i is perfect number)
explain2 => we have to clear our list before we can check if the next number i is a perfect number or not so that factors of the previous number does not interfere with factors of the current number.
int start=1;
int end=50;
for(int a=end ; a > start ;a--)
{
int b=1;
int c=0;
bool x=false;
for(int i=1 ; i < a ;i++)
{
b=a/i;
if(b*i==a)
{
c+=i;
}
if(c==a & i==a/2)
{
x=true;
}
}
if(x==true)
Console.Write("{0} is : {1}",a,x);
}