• JAVA 大数运算模板 ACM竞赛必备


    Ⅰ基本函数:

    1.valueOf(parament); 将参数转换为制定的类型

    比如 int a=3;

    BigInteger b=BigInteger.valueOf(a);

    则b=3;

    String s=”12345”;

    BigInteger c=BigInteger.valueOf(s);

    则c=12345;

    1.赋值:

    BigInteger a=new BigInteger("1");

    BigInteger b=BigInteger.valueOf(1);

    2.运算:

    ① add(); 大整数相加 
    BigInteger a=new BigInteger(“23”); 
    BigInteger b=new BigInteger(“34”); 
    a. add(b);

    ②subtract(); 相减 
    ③multiply(); 相乘 
    ④divide(); 相除取整 
    ⑤remainder(); 取余 
    ⑥pow(); a.pow(b)=a^b 
    ⑦gcd(); 最大公约数 
    ⑧abs(); 绝对值 
    ⑨negate(); 取反数 
    ⑩mod(); a.mod(b)=a%b=a.remainder(b); 

    3.BigInteger构造函数: 
    一般用到以下两种: 
    BigInteger(String val); 
    将指定字符串转换为十进制表示形式; 
    BigInteger(String val,int radix); 
    将指定基数的 BigInteger 的字符串表示形式转换为 BigInteger 
    4.基本常量: 
    A=BigInteger.ONE 1 
    B=BigInteger.TEN 10 
    C=BigInteger.ZERO 0 

    5.n.compareTo(BigInteger.ZERO)==0  //相当于n==0

    6.if(a[i].compareTo(n)>=0 &&a[i].compareTo(m)<=0)   // a[i]>=n && a[i]<=m 

    public class 大数计算 {
    
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner cin = new Scanner(System.in);
    BigInteger a, b;
    while(cin.hasNext())//相当于c语言中的scanf("%d", &n) != EOF
    {
    a = cin.nextBigInteger();
    b = cin.nextBigInteger();
    
    System.out.println(a.add(b));//大整数加法
    
    System.out.println(a.subtract(b));//大整数减法
    
    System.out.println(a.multiply(b));//大整数乘法
    
    System.out.println(a.divide(b));//大整数除法,取整
    
    System.out.println(a.remainder(b));//大整数取模
    
    System.out.println(a.abs());//对大整数a取绝对值
    
    int x = 0;
    System.out.println(a.pow(x));//大整数a的x次幂
    
    int y = 8;
    System.out.println(a.toString(y));//返回大整数a的p进制用字符串表现的形式
    System.out.println(a.toString());//返回大整数a的十进制用字符串表现的形式
    
    //大整数之间的比较
    if( a.compareTo(b) == 0 ) System.out.println("a == b"); //大整数a==b
    
            else if( a.compareTo(b) > 0 ) System.out.println("a > b"); //大整数a>b
    
            else if( a.compareTo(b) < 0 ) System.out.println("a < b"); //大整数a<b)
    
    
    
    BigDecimal c, d;
    c = cin.nextBigDecimal();
    d = cin.nextBigDecimal();
    System.out.println(c.add(d));//浮点数相加
    
    System.out.println(c.subtract(d));//浮点数相减
    
    System.out.println(c.multiply(d));//浮点数相乘
    
    }
    }
    }
  • 相关阅读:
    java冒泡算法和选择排序法
    JDBC操作数据库,比如修改电商数据库中的分类的id,让各商品随机
    RF使用
    安装RF框架(基于Python)
    selenium+java的常使用的一些操作
    selenium的常用操作
    selenium的8种定位方式(java举例)
    服务管理
    Linux软件安装
    项目依赖
  • 原文地址:https://www.cnblogs.com/Romantic-Chopin/p/12451430.html
Copyright © 2020-2023  润新知