題目概要:
給一個數字N(範圍1<=N<=2*10^100),求出1^1+2^2+3^3+......+N^N的個位數。
解題方向:
由於題目會給超過int以及long的範圍,所以只能用字串來處理。個位數為20個一循環,所以可以自己建一個表格。自己寫一個字串長除法,求出商數以及餘數。因為答案只需要個位數,所以只需要把商數的個位數乘上94(1~20個位數總和)加上1~餘數的個位數總和。因為題目只要個位數,印出個位數極為答案,十位數以上的數字不必在乎為多少。
程式碼:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Java | |
import java.util.Scanner; | |
class uva10162{ | |
public static void main(String args[]){ | |
Scanner sc=new Scanner(System.in); | |
String st; | |
int table[]={1,4,7,6,5,6,3,6,9,0,1,6,3,6,5,6,7,4,9,0}; | |
while(sc.hasNext()){ | |
st=sc.next(); | |
if(st.equals("0"))break; | |
String Q=""; | |
int R=0; | |
// 長除法start | |
while(true){ | |
for(int i=0;i<2;i++){ | |
R=R*10+st.charAt(0)-48; | |
st=st.substring(1); | |
if(st.equals("")) break; | |
} | |
if(R>=20){ | |
Q=Q+(char)R/20; | |
R=R%20; | |
}else{ | |
if(!st.equals("")){ | |
R=R*10+st.charAt(0)-48; | |
st=st.substring(1); | |
} | |
Q=Q+(char)R/20; | |
R=R%20; | |
} | |
if(st.equals("")) break; | |
} | |
//取出商數最後一位數 | |
char last=Q.charAt(Q.length()-1); | |
//加總答案 | |
int ans=0; | |
ans=(last-48)*94; | |
for(int i=0;i<R;i++){ | |
ans=ans+table[i]; | |
} | |
//取出個位數 | |
while(ans>10){ | |
ans=ans%10; | |
} | |
System.out.println(ans); | |
} | |
} | |
} |
文章標籤
全站熱搜