Click here to Skip to main content
15,923,164 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi...I just done a code to find a perfect number in C#..But its lengthy...So i want to develop this Using Linq...Here i added my code also...Please Help me..
C#
static void Main(string[] args)
        {
            int number, sumofnumbers, i;
            Console.WriteLine("hello");
            for (number = 2; number <= 100000; number++)
            {
                i = 1;
                sumofnumbers = 0;
                while (i < number)
                {

                    if (number % i == 0)
                        sumofnumbers = sumofnumbers + i;
                    i++;
                }
                if (sumofnumbers == number)
                    Console.WriteLine("perfect number is " + number);
            }
        }

Thanks in advance
Posted
Updated 23-Jan-15 1:15am
v2

1 solution

How about:
C#
IEnumerable<int> perfectNumbers = Enumerable.Range(2, 100000)
    .Where(number => Enumerable.Range(1, number - 1).Where(i => (number % i) == 0).Sum() == number);

foreach (int number in perfectNumbers)
{
    Console.WriteLine("perfect number is " + number);
}
 
Share this answer
 
Comments
BillWoodruff 23-Jan-15 8:29am    
+5 This is a Zen Koan ! Congratulations (in case I didn't say it already) on your MVP status for this year.
Shivaram_i 23-Jan-15 9:18am    
What??? #BillWoodruff
BillWoodruff 23-Jan-15 11:48am    
I am expressing my appreciation for Richard's very advanced example here which demonstrates the power of Linq.
Shivaram_i 23-Jan-15 9:18am    
Hey thank you Richard...But its little bit confusion...Will you please explain This...??
I mean In this Line ".Where(number => Enumerable.Range(1, number - 1).Where(i => (number % i) == 0).Sum() == number);"
In first case number is 2 and i is 1 right???But how It will taken like this only...If am wrong then tell me what value variable i has been taken and how it will increment???Sorry because i am not aware of this LINQ...So

Thanks
Richard Deeming 23-Jan-15 9:25am    
The LINQ version is the equivalent to your original loop. It's shorter than the original, but not necessarily easier to understand. :)

* Loop through 100000 numbers starting at 2: Enumerable.Range(2, 100000)
* For each number in the outer loop:
*- Loop through the integers from 1 to number - 1: Enumerable.Range(1, number - 1)
*- Filter it to only include numbers by which the outer number is divisible: .Where(i => (number % i) == 0)
*- Take the sum of the matching numbers in the inner loop: .Sum()
* Filter the outer loop to numbers where the number is equal to the inner sum: .Where(number => ... == number)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900