gpt4 book ai didi

Project Euler Q20 的 Java 算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:20:03 28 4
gpt4 key购买 nike

n!表示 n X (n - 1) X ... X 3 X 2 X 1

例如,10! = 10 X 9 X ... X 3 X 2 X 1 = 3628800, 和数字10中的数字总和!是 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.

求数字100中各位数字的和!

import java.util.*;
class ProjectEuler_20{
public static double factorial(double number){
double num=1;
for(int i=2;i<=number;i++){
num=num*i;
}
return num;
}
public static void main(String args[]){
double number=factorial(100);
long num=(long)number;
long sum=0;
for(int i=0;num>0;i++){
sum=sum+num%10;
num=num/10;
}
System.out.println(sum);
}
}

为什么我总是得到Long.MAX_VALUE的位数之和?有没有办法接近真正的答案?

最佳答案

double 不能准确地容纳大到 100! 的数字;它只能容纳一个近似值

您必须使用 BigInteger 才能准确地执行计算。

这是 1 行答案:

int sum = IntStream.range(1, 101)       // stream ints from 1 up to 100
.mapToObj(String::valueOf) // ready for BigInteger constructor
.map(BigInteger::new) // create a BigInteger from the String
.reduce(BigInteger::multiply) // multiply them all together
.get().toString().chars() // stream the digits of the result
.map(i -> i - '0') // convert char as int to its digit value
.sum(); // sum the digits

结果:

648

fyi, 100! is 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

关于Project Euler Q20 的 Java 算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35473564/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com