// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Text; using Microsoft.FSharp.Math; namespace E { public static class MyBigNumExts { public static string MyToString(this BigNum x, int nodec) { StringBuilder sb = new StringBuilder(); BigInt n = x.Numerator; BigInt d = x.Denominator; BigInt intpart = n / d; sb.Append(intpart.ToString()); n = n - intpart * d; sb.Append("."); for (int i = 0; i < nodec; i++) { n = n * BigInt.FromInt32(10); intpart = n / d; sb.Append(intpart.ToString()); n = n - intpart * d; } return sb.ToString(); } public static BigNum Sqrt(BigNum x, int nodec) { BigInt precision = BigInt.Parse("1".PadRight(nodec, '0')); BigNum curr = x / BigNum.Parse("10"); BigNum last; BigNum tmp; do { last = curr; curr = (last + x / last) / BigNum.Parse("2"); tmp = curr - last; if (tmp.IsNegative) tmp = -tmp; } while (tmp.Numerator * precision > tmp.Denominator); return curr; } public static BigNum Pow(BigNum x, BigNum y, int nodec) { BigInt n = y.Numerator; BigInt d = y.Denominator; if (n == BigInt.Zero) { return BigNum.One; } else if (n % d == BigInt.Zero) { if (y.ToString().Length > 9) throw new ArgumentException(y + " is too big an int"); return BigNum.PowN(x, int.Parse(y.ToString())); } else if ((BigInt.Parse("2") * n) % d == BigInt.Zero) { return Sqrt(x, nodec) * Pow(x, y - BigNum.Parse("1/2"), nodec); } else { throw new ArgumentException(y + " is not int or int + half"); } } } public class Program { public static void Main(string[] args) { Console.WriteLine(MyBigNumExts.Sqrt(BigNum.Parse("4"), 30).MyToString(30)); Console.WriteLine(MyBigNumExts.Sqrt(BigNum.Parse("2"), 30).MyToString(30)); Console.WriteLine(MyBigNumExts.Pow(BigNum.Parse("4"), BigNum.Parse("1/2"), 30).MyToString(30)); Console.WriteLine(MyBigNumExts.Pow(BigNum.Parse("4"), BigNum.Parse("1"), 30).MyToString(30)); Console.WriteLine(MyBigNumExts.Pow(BigNum.Parse("4"), BigNum.Parse("3/2"), 30).MyToString(30)); Console.WriteLine(MyBigNumExts.Pow(BigNum.Parse("4"), BigNum.Parse("2"), 30).MyToString(30)); Console.WriteLine(MyBigNumExts.Pow(BigNum.Parse("2"), BigNum.Parse("1/2"), 30).MyToString(30)); Console.WriteLine(MyBigNumExts.Pow(BigNum.Parse("2"), BigNum.Parse("1"), 30).MyToString(30)); Console.WriteLine(MyBigNumExts.Pow(BigNum.Parse("2"), BigNum.Parse("3/2"), 30).MyToString(30)); Console.WriteLine(MyBigNumExts.Pow(BigNum.Parse("2"), BigNum.Parse("2"), 30).MyToString(30)); } } }