java - 如何使用java或c计算3^1002的数字之和?

标签 java c++ c

由于java或c中的数据类型无法处理这么大的数字。我可以使用什么逻辑来求数字之和?

最佳答案

试试这个:

BigInteger big = BigInteger.valueOf(3).pow(1002)

BigInteger

Immutable arbitrary-precision integers. All operations behave as if BigIntegers were represented in two's-complement notation (like Java's primitive integer types). BigInteger provides analogues to all of Java's primitive integer operators, and all relevant methods from java.lang.Math. Additionally, BigInteger provides operations for modular arithmetic, GCD calculation, primality testing, prime generation, bit manipulation, and a few other miscellaneous operations.

您想要将 3^1002 中的数字之和相加。试试这个:

public static void main(String[] args) throws ParseException {
    BigInteger big = BigInteger.valueOf(3).pow(1002);
    String s = big.toString();
    System.out.println("3^1002 :-" + big);
    int sum = 0;
    for (int i = 0; i < s.length(); i++) {
        sum = sum + Integer.parseInt(String.valueOf(s.charAt(i)));

    }
    System.out.println("Sum of digits = "+sum);
}

输出:

3^1002 :-11898637375327259732014097337769299293688798294769333508984283314041457376120344095867004824655472557675187999271853241203558591238905570206788084527321583066248582026784887234902132968060683571469513601058297562370160530340607849942554095557486780070414555603129323099649923489573350062357188314294245225987472417074007240612055747584770991072267007636764090438484359179546617239448259650885170465292981543834807042949776925329153470838724492488095529295189557924920125696980009
Sum of digits = 2214

关于java - 如何使用java或c计算3^1002的数字之和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16238495/

相关文章:

c++ - c 中的 union 一次存储一个数据

C++14遇到奇怪的 "use of deleted function"错误

c - 头文件和标准库

java - MacOS 雪豹和 Eclipse : Error starting Eclipse (No Java virtual machine. ...)

java - 将字符串值从 spring bean 传递到 java 方法

c++ - gcc优化?漏洞?及其对项目的实际意义

c - C 中的定时器库

c - 在 CLion 中使用 stdin 运行

java - 使用 java 代码 (ejbca) 将 pfx 证书保存到文件

java - 创建两个 RoundedField,JTextField 和 JPasswordField