由于java或c中的数据类型无法处理这么大的数字。我可以使用什么逻辑来求数字之和?
最佳答案
试试这个:
BigInteger big = BigInteger.valueOf(3).pow(1002)
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/