2 ms·
Here's a C# example: using System.Numerics; using System; var myBigStartingNumber = BigInteger.Parse("12893123812148934789012378957891325789012357891238
by bob1029 5y ago
Here's a C# example:
using System.Numerics;
using System;
var myBigStartingNumber = BigInteger.Parse("12893123812148934789012378957891325789012357891238912319824589123589012358915891589158989125");
Collatz(myBigStartingNumber);
Console.WriteLine("Collatz returned 1");
static int Collatz(BigInteger x)
{
Console.WriteLine(x);
return x == 1 ? 1 : x % 2 == 0 ? Collatz(x / 2) : Collatz(3 * x + 1);
}
(stack overflows virtually guaranteed!)
- vintermann 5y agoYes, unless C# does tail call elimination (it doesn't, right? I'm a bit behind the times on such things) that will blow through the stack very quickly. But something which is worth doing while playing with such programs, (besides writing it nonrecursively), is looking into alternative BigNum representations. Tree based number representations can make huge numbers expressible through few operations much smaller, at the cost of making "typical" numbers (those that can't be expressed by arithmetic expressions much shorter than themselves) only slightly larger. Knuth made one such representation, called TCALC, which lets you do arithmetic on numbers far too large to fit into computer memory in regular byte string bignum representation. A US academic, Paul Tarau, has made similar huge-num libraries (slightly more elegant since representations are unique) for modern programming languages.