计蒜之道第四场第二题:遗失的支付宝密码

本文介绍了一个使用Java进行数列计算的例子,特别是如何利用BigInteger处理可能溢出的大整数运算。通过迭代计算数列的每一项,并求和,展示了BigInteger在解决大数问题中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这是第一题简单的数据在

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		int n;
		BigInteger m;
		int Max = (int) Math.pow(2, 32);
		int sum;
		System.out.println( (Math.pow(10, 9)*Math.pow(10, 9))>Math.pow(2, 32));
		while (scanner.hasNext()) {
			n = scanner.nextInt();
			m = new BigInteger(scanner.nextInt()+"");
			sum = 0;
			BigInteger a[] = new BigInteger[n+1];
			a[0] = m;
			
			for (int i = 1; i < a.length; i++) {
				if(i%2 == 1){
					if(i==1){
						a[i] = 1*m;
					}else{
						a[i] = a[i-1]*m<0?((a[i-1]%Max)*(m%Max))%Max:a[i-1]*m;
					}
				}else{
					a[i] = (a[i-1]*m-a[i-2])<0?((a[i-1]%Max)*(m%Max))%Max:(a[i-1]*m-a[i-2]);
				}
			}
			
			for (int i = 1; i < a.length; i++) {
				sum = (sum+a[i])<0?(sum%Max+a[i]%Max)%Max:(sum+a[i]);
			}

			for (int i = 0; i < a.length; i++) {
				System.out.print(a[i]+" ");
			}
			System.out.println(sum);
		}
	}
还有中等的和困难的都只过了一组数据。。

不知为什么错了,希望有人能指出来。

import java.math.BigInteger;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		int n;
		BigInteger m;
		BigInteger Max = new BigInteger(Integer.MAX_VALUE+"");
		BigInteger sum;
		while (scanner.hasNext()) {
			n = scanner.nextInt();
			m = scanner.nextBigInteger();
			sum = new BigInteger("0");
			BigInteger a[] = new BigInteger[n+1];
			a[0] = m;
			
			for (int i = 1; i < a.length; i++) {
				if(i%2 == 1){
					if(i==1){
						a[i] = m;
					}else{
						a[i] = a[i-1].multiply(m);
					}
				}else{
					a[i] = a[i-1].multiply(m).subtract(a[i-2]);
				}
			}
			
			for (int i = 1; i < a.length; i++) {
				sum = sum.add(a[i]).mod(Max);
			}

			/*for (int i = 0; i < a.length; i++) {
				System.out.print(a[i]+" ");
			}*/
			System.out.println(sum);
		}
	}
}

只过了一组。。。


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值