Last active
August 29, 2015 14:22
-
-
Save CryZe/25265a67d03dcfb07e62 to your computer and use it in GitHub Desktop.
Lychrel Numbers
This file contains 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.Generic; | |
using System.Linq; | |
using System.Numerics; | |
using static System.Linq.Enumerable; | |
using static System.Numerics.BigInteger; | |
using static System.Console; | |
namespace LychrelNumbers | |
{ | |
class Program | |
{ | |
private static IEnumerable<int> GetAllPositiveIntegers() | |
{ | |
return Range(0, int.MaxValue); | |
} | |
private static string Revert(string text) | |
{ | |
return new string(text.Reverse().ToArray()); | |
} | |
private static bool IsPalindrome(BigInteger number) | |
{ | |
var stringified = number.ToString(); | |
return stringified == Revert(stringified); | |
} | |
private static BigInteger RevertAndAdd(BigInteger number) | |
{ | |
var stringified = number.ToString(); | |
var reverted = Revert(stringified); | |
var revertedNumber = Parse(reverted); | |
return number + revertedNumber; | |
} | |
private static bool IsLychrelNumber(int x) | |
{ | |
BigInteger number = x; | |
foreach (var i in Range(0, 50)) | |
{ | |
number = RevertAndAdd(number); | |
if (IsPalindrome(number)) | |
return false; | |
} | |
return true; | |
} | |
static IEnumerable<int> GetLychrelNumbers() | |
{ | |
return GetAllPositiveIntegers() | |
.Where(x => IsLychrelNumber(x)); | |
} | |
static void Main(string[] args) | |
{ | |
var threshold = 100000; | |
var lychrelNumbersUnderThreshold = GetLychrelNumbers() | |
.TakeWhile(x => x < threshold) | |
.ToList(); | |
foreach (var lychrelNumber in lychrelNumbersUnderThreshold) | |
{ | |
WriteLine(lychrelNumber); | |
} | |
WriteLine($"There's { lychrelNumbersUnderThreshold.Count } Lychrel Numbers under { threshold }."); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment