Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

High precision integer math in C#?

Tags:

c#

types

I have a very large number I need to calculate, and none of the inbuilt datatypes in C# can handle such a large number.

Basicly I want to solve this:

Project Euler 16:

2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.

What is the sum of the digits of the number 2^1000?

I have already written the code, but, as said before, the number is too large for c# datatypes. The code has been tested and verified with small numbers (such as 2^15) and it works perfectly.

using System;

namespace _16_2E1000
{
    class Program
    {
        static void Main(string[] args)
        {
            ulong sum = 0;
            ulong i = 1 << 1000;
            string s = i.ToString();
            foreach (char c in s)
            {
                sum += (ulong) Convert.ToInt64(c.ToString());
            }
            Console.WriteLine(sum);
            Console.ReadLine();
        }
    }
}
like image 846
CasperT Avatar asked Apr 16 '26 07:04

CasperT


1 Answers

You can use BigInteger from the J# classes. First question in this article tells you how. It's a bit of pain b/c then you have to provide the J# redistributable when you roll out tho.

like image 176
JP Alioto Avatar answered Apr 18 '26 19:04

JP Alioto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!