輸入n,計算S=1!+2!+3!+…+n!的末6位(不含前導0)。n≤106,n!表示前n個正整數之積。數據結構
首先是要求階乘和最後求末六位,可是注意到n≤106,因此計算和的時候只須要加上後六位就行(由於第七位以前的必定會被模),這樣也保證了使用int類型不會溢出。函數
public static void main(String[] args) { Scanner scn=new Scanner(System.in); int n=scn.nextInt(); int i=1,s=1,sum=0; //計算n的階乘和 while(i<=n){ s*=i; s%=1000000; sum+=s; i++; } //計算後六位 sum%=1000000; System.out.println(sum); }
猴子吃桃。有一羣猴子摘來了一批桃子,猴王規定天天只准吃一半加一隻(即次日吃剩下的一半加一隻,以此類推),第九天正好吃完,問猴子們摘來了多少桃子?編寫遞歸函數實現問題this
天天吃一半加一隻,則次日也是吃第一天吃完的剩下的一半加一隻。很明顯,這個問題在每一天時都是重複的子問題。問題要求用遞歸函數實現問題。很容易想到遞歸出口就是第九天桃子數等於0,n==9時,f(n)=0。而遞歸公式就是f(n)=f(n-1)/2-1。摘來的桃子數就是f(0)。code
/** * 表示第n天的桃子數 * @param n 第n天 * @return 桃子數 */ public static int f(int n) { if(n==9) return 0; return 2*(1+f(n+1)); }
給定若干矩陣的行數和列數,要去給出一種計算方法,即加括號的表達式,計算按照這個表達式的順序計算,應該計算多少次基本的實數乘積。例如:A是5010的,B是1020的,C是205。則(A(BC))的乘法次數爲10205(BC的乘法次數)+ 5010*5((A(BC))的乘法次數)= 3500blog
使用棧的數據結構。遇到字母時入棧,遇到右括號時出棧並計算,而後將結果入棧。由於輸入保證合法,括號無須入棧。遞歸
static class Juzhen{ int x; int y; Juzhen cal(Juzhen another) { if(this.y!=another.x) return null; num+=x*y*another.y; return new Juzhen(x,another.y); } public Juzhen(int x, int y) { this.x = x; this.y = y; } } private static int num=0; private static Map<String,Juzhen> map=new HashMap(); public static void getNum(String exp) { Stack<Juzhen> s=new Stack<Juzhen>(); int i=0; s.add(null); while(i<exp.length()) { if(exp.charAt(i)=='('){//入棧 s.add(null); }else if(exp.charAt(i)==')') {//出棧 Juzhen p1=s.pop(); Juzhen p2=s.pop(); s.add(p2.cal(p1)); }else {//字母 Juzhen t=map.get(exp.charAt(i)+""); Juzhen p=s.pop(); if(p!=null) s.add(p.cal(t)); else s.add(t); } i++; } } public static void main(String[] args) { map.put("A", new Juzhen(50,10)); map.put("B", new Juzhen(10,20)); map.put("C", new Juzhen(20,5)); getNum("A(BC)"); System.out.println(num); }