C#实现大数字运算的实例代码
c#实现大数字的运算
1、添加引用:system.numerics.dll
2、添加命名空间:using system.numerics;
3、实例:
3.1判断一个数字是不是质数
static void main(string[] args)
{
console.writeline("请输入一个很大的数字:");
string bignumber = console.readline();
biginteger biginteger = biginteger.parse(bignumber);
bool isnumber=false;
for (biginteger i = 2; i < biginteger.pow(biginteger, 2);i++ )
{
if (biginteger % i == 0)
{
isnumber = true;
break;
}
}
if (isnumber)
{
console.writeline("不是质数");
}
else
{
console.writeline("是质数");
}
console.readline();
}
3.2实现两个大数的加减乘除
static void main(string[] args)
{
console.write("请输入第一个大数字:");
string bignum1 = console.readline();
biginteger bigint1 = biginteger.parse(bignum1);
console.write("请输入第二个大数字:");
string bignum2 = console.readline();
biginteger bigint2 = biginteger.parse(bignum2);
console.write(environment.newline);
biginteger addnum = bigint1 + bigint2;
biginteger subnum = bigint1 - bigint2;
biginteger purnum = bigint1 * bigint2;
biginteger divnum = bigint1 / bigint2;
console.writeline("两大数相加结果为:{0}",addnum);
console.writeline("两大数相减结果为:{0}",subnum);
console.writeline("两大数相乘结果为:{0}",purnum);
console.writeline("两大数相除结果为:{0}",divnum);
console.readline();
}