Skip to content

Instantly share code, notes, and snippets.

@johnnykv
Created September 5, 2011 09:28
Show Gist options
  • Save johnnykv/1194553 to your computer and use it in GitHub Desktop.
Save johnnykv/1194553 to your computer and use it in GitHub Desktop.
Simpel BigInt implementation i C#
//Johnny Vestergaard - 2011
// Simpel BigInt implementation i C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace tmpOperatorOverload
{
class Program
{
static void Main(string[] args)
{
BigInt bigInt = new BigInt("1000");
BigInt bigInt2 = new BigInt("3000");
BigInt newBigInt = bigInt + bigInt2;
Console.WriteLine("Resultater er: {0}", newBigInt.ToString());
Console.ReadLine();
}
}
class BigInt
{
//max størrelse: 256 tegn
const int arraySize = 256;
internal int[] intArray = new int[arraySize];
//opret instans ved successivt at konvertere og
//lægge de enkelte tegn over i vores interne intArray.
public BigInt(string stringTal)
{
int y = stringTal.Length - 1;
for (int x = 0; x < stringTal.Length; x++, y--)
{
intArray[x] = Int32.Parse(stringTal[y].ToString());
}
}
//opret instans ved at passe en reference til et allerede
//eksisterende int array.
public BigInt(int[] intArray)
{
this.intArray = intArray;
}
//Adderings operationen.
public static BigInt operator+(BigInt bigInt1, BigInt bigInt2)
{
//Array som benytes til resultatet.
int[] result = new int[arraySize];
//Carray aka. "Rest" på dansk.
int carry = 0;
//Iterere de 2 arrays igennem og læg de enkelte tal sammen.
//(og overfør resten til venstre - som ved normal hovedregning)
for (int x = 0; x < bigInt2.intArray.Length; x++)
{
int tmpResult = bigInt1.intArray[x] + bigInt2.intArray[x] + carry;
//Over 9 - vi har en rest!
if (tmpResult > 9)
{
if (x == bigInt2.intArray.Length - 1)
throw new OverflowException("Der er for mange tegn til at resultatet " +
"kan indholdes i denne BigInt!");
carry = 1;
result[x] = tmpResult - 10;
}
else
{
result[x] = tmpResult;
carry = 0;
}
}
return new BigInt(result);
}
public override string ToString()
{
string returnString = "";
//Udskrivning af værdi som string.
//Bemærk at
for (int x = intArray.Length - 1; x >= 0; x--)
{
returnString += intArray[x].ToString();
}
return returnString;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment