求平方和
public static void main(String[] args) throws IOException { int n; String s; BufferedReader buf; buf=new BufferedReader(new InputStreamReader(System.in)); System.out.print("请输入一个自然数:"); s=buf.readLine(); n=Integer.parseInt(s); System.out.print("f(n)=1"); for(int i=2;i<=n;i++) System.out.print("+"+i*i); System.out.print("="+Square(n)); } public static long Square(int n) { long f=0; if(n<0) System.out.println("n<0,输入错误!"); else if (n==1)f=1; else f=Square(n-1)+n*n; return f; }
穷举质数
public static void main(String args[]) { int i,j; for(j=2;;j++) { for(i=2;i<=j/2;i++) { if(j%i==0) break; } if(i>j/2) { System.out.println(j); } } }
求质因子
public static void main(String[] args) { int n = 0; String s = null; BufferedReader buf; buf=new BufferedReader(new InputStreamReader(System.in)); System.out.print("请输入一个数:"); try { s=buf.readLine(); } catch (IOException e) { e.printStackTrace(); } n=Integer.parseInt(s); int temp = n; for (int i = 2; i <= temp; i++) { if (!isPrime(i)) { continue; } while (true) { if (temp%i == 0) { temp = temp/i; System.out.println(i); } else { break; } } } } public static boolean isPrime(int n) { int i; for (i = 2; i <= n; i++) { if (n%i == 0) { break; } } if (i >= n) { return true; } else { return false; } }