Created
June 5, 2013 06:14
-
-
Save fuzeman/5711942 to your computer and use it in GitHub Desktop.
CodeEval Prime Palindrome (003)
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.Linq; | |
namespace Solutions.PrimePalindrome | |
{ | |
public class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Console.Write(PrimePalindrome.Solve()); | |
} | |
} | |
public class PrimePalindrome | |
{ | |
public static string Solve() | |
{ | |
return Enumerable.Range(1, 1000).Reverse() | |
.FirstOrDefault(n => IsPalindrome(n) && IsPrime(n)) | |
.ToString(); | |
} | |
public static bool IsPalindrome(int n) | |
{ | |
var ns = n.ToString(); | |
return ns == new String(ns.Reverse().ToArray()); | |
} | |
public static bool IsPrime(int n) | |
{ | |
if ((n & 1) == 0) | |
return n == 2; | |
for (var i = 3; (i*i) <= n; i += 2) | |
{ | |
if ((n%i) == 0) | |
return false; | |
} | |
return n != 1; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment