Created
February 15, 2020 09:58
-
-
Save ertugrulozcan/1e0f07408a8585b7edab2e3e1d948571 to your computer and use it in GitHub Desktop.
PerfectNumbers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using NUnit.Framework; | |
namespace Tests | |
{ | |
public class PerfectionTest | |
{ | |
[SetUp] | |
public void Setup() | |
{ | |
} | |
[Test] | |
public void PerfectNumberTest() | |
{ | |
Assert.IsTrue(ObssConsoleApp.PerfectNumber.IsPerfectNumber(6)); | |
Assert.IsTrue(ObssConsoleApp.PerfectNumber.IsPerfectNumber(28)); | |
Assert.IsTrue(ObssConsoleApp.PerfectNumber.IsPerfectNumber(496)); | |
Assert.IsFalse(ObssConsoleApp.PerfectNumber.IsPerfectNumber(10)); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Runtime.CompilerServices; | |
namespace ObssConsoleApp | |
{ | |
public static class PerfectNumber | |
{ | |
#region Methods | |
public static bool IsPerfectNumber(int number) | |
{ | |
var multipliers = FindMultipliers(number); | |
if (multipliers == null || !multipliers.Any()) | |
{ | |
return false; | |
} | |
return multipliers.Sum() == number; | |
} | |
public static IEnumerable<int> FindMultipliers(int number) | |
{ | |
if (PrimeNumbers.IsPrime(number)) | |
{ | |
return new[] { number }; | |
} | |
List<int> result = new List<int>(); | |
for (int i = 2; i < number / 2; i++) | |
{ | |
if (number % i == 0) | |
{ | |
result.Add(i); | |
} | |
} | |
if (result.Any() && !result.Contains(1)) | |
{ | |
result.Add(1); | |
} | |
return result; | |
} | |
#endregion | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment