As stated in problem 37 at Project Euler:
The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3.
I already solved this problem (answer ends with 7 :-), but a doubt remains: how efficiently left/right truncate a number, WITHOUT using strings? I built following code, but it seems ugly:
public static void Main()
{
Console.WriteLine( // 3797, 379, 37, 3, 797, 97, 7
String.Join(", ", 3797L.Truncate().ToArray()));
Console.ReadLine();
}
static IEnumerable<long> Truncate(this long number)
{
yield return number;
long aux = number;
while ((aux /= 10) > 0) // right to left
yield return aux;
// god forgive me, but it works
while ((number = (number.Reverse() / 10).Reverse()) > 0) // left to right
{
yield return number;
}
}
public static long Reverse(this long number)
{
long reverse = number % 10;
number = number / 10;
while (number != 0)
{
reverse = (number % 10) + (10 * reverse);
number = number / 10;
}
return reverse;
}
EDIT: I ended with this code:
static IEnumerable<long> Truncate(this long number)
{
yield return number;
int i = 10;
while (number / i > 0)
{
yield return number / i;
yield return number % i;
i *= 10;
}
}