51nod 2187 Project Euler 56 考虑最大 的a^b个位和是多少

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_43691058/article/details/98595053

51nod 2187 :考虑最大 的a^b个位和是多少

在这里插入图片描述
在这里插入图片描述

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

/*
 * 对于每组数据,输出n!的各位和。
 */
public class Main {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int T = in.nextInt();
		while ((T--) > 0) {
			int n = in.nextInt();
			System.out.println(f(n));
		}
	}

	// 计算n!的各位和
	private static int f(int n) {
		BigInteger T = BigInteger.ZERO;//中间量
		int max = 0, temp = 0,sum=0;
		for (int a = 1; a < n; a++) {
			for (int b = 1; b < n; b++) {
				T=BigInteger.valueOf(a).pow(b);//计算a^b
				sum=myadd(T.toString());//结果转换为字符串传入myadd
				if(sum>max){
					max =sum;
				}
			}
		}
		return max;
	}
	
	//该函数实现字符串转化为字符数组,并求各位和
	private static int myadd(String s) {
		int sum = 0;
		char ch[]  = s.toCharArray();//s转换为字符数组
		for(int i=0;i<ch.length;i++){
			sum += ch[i]-48;
		}
		return sum;
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_43691058/article/details/98595053