首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >我想在JAVA中取出存储在BigInteger中的大数字的最后一位

我想在JAVA中取出存储在BigInteger中的大数字的最后一位
EN

Stack Overflow用户
提问于 2018-08-01 20:20:58
回答 4查看 800关注 0票数 0
代码语言:javascript
复制
import java.math.BigInteger;
import java.util.Scanner;

public class LastFact
{
    // Returns Factorial of N
    static BigInteger factorial(int N)
    {
        // Initialize result
        BigInteger f = new BigInteger("1"); // Or BigInteger.ONE

        // Multiply f with 2, 3, ...N
        for (int i = 2; i <= N; i++)
            f = f.multiply(BigInteger.valueOf(i));

        return f;
    }

    // Driver method
    public static void main(String args[]) throws Exception
    {
        int N = 300;

        System.out.println(factorial(N));
    }
}
EN

回答 4

Stack Overflow用户

发布于 2018-08-01 20:26:36

如果您想要删除BigInteger的最后一位N数字,请将其除以10^N,例如,删除最后两位数字除以10^2=100

代码语言:javascript
复制
BigInteger i = new BigInteger("123456");
BigInteger j = i.divide(BigInteger.valueOf(100)); // j=1234 

要获得要删除的提醒,请改用reminder()方法:

代码语言:javascript
复制
BigInteger i = new BigInteger("123456");
BigInteger j = i.reminder(BigInteger.valueOf(100)); // j=56 

请注意,由于您正在计算较大的阶乘,因此您可能希望使用Stirling's approximation

票数 1
EN

Stack Overflow用户

发布于 2018-08-01 20:26:44

取最后一位数,得到BigInteger除以10后的余数

代码语言:javascript
复制
System.out.println(f.remainder(BigInteger.TEN));
票数 1
EN

Stack Overflow用户

发布于 2018-08-01 20:28:43

将你的大整数转换成字符串,然后取最后一个数字。

代码语言:javascript
复制
public static void main(String args[]) throws Exception
{
    int N = 300;

        String bigNumber = factorial(N).toString();
        String lastNumberStr = bigNumber.charAt(bigNumber.length()-1)+"";
        int lastNumber = Integer.parseInt(lastNumberStr);

        System.out.println(lastNumber);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51633188

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档