Skip to content

Instantly share code, notes, and snippets.

@leohxj
Created December 24, 2012 07:15
Show Gist options
  • Save leohxj/4368182 to your computer and use it in GitHub Desktop.
Save leohxj/4368182 to your computer and use it in GitHub Desktop.
数列求和
/**
* 求FebonacciSequence数列
*/
import java.util.Scanner;
public class FibonacciSequenceSum {
public static void main(String[] args) {
long sum;
while (true) {
System.out.println("请输入数列的项数(输入-1结束):");
Scanner sin = new Scanner(System.in);
int num = sin.nextInt();
if (num == -1) {
break;
} else {
long start = System.currentTimeMillis();
sum = getFibonacciSequenceSum(num);
long stop = System.currentTimeMillis();
long time = stop - start;
System.out.println("sum=" + sum + "\ntime=" + time);
}
}
while (true) {
System.out.println("请输入数列的项数(输入-1结束):");
Scanner sin = new Scanner(System.in);
int num = sin.nextInt();
if (num == -1) {
break;
} else {
long start = System.currentTimeMillis();
sum = CallFibocacci(num);
long stop = System.currentTimeMillis();
long time = stop - start;
System.out.println("sum=" + sum + "\ntime=" + time);
}
}
}
public int getFebio(int n) {
int sum = 0;
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
} else {
return getFebio(n - 1) + getFebio(n - 2);
}
}
private static long getFibonacciSequenceSum(int num) {
long num1 = 1;
long num2 = 1;
long temp = 0;
long sum = 0;
if (num == 1) {
sum = 1;
System.out.println(num1);
} else {
sum = num1 + num2;
System.out.print(num1 + "," + num2);
}
for (int i = 3; i <= num; i++) {
temp = num2;
num2 = num1 + num2;
num1 = temp;
sum += num2;
System.out.print("," + num2);
}
System.out.println();
return sum;
}
public static long fibonacci(int iNum)
{
if(iNum == 1) return 1;
if(iNum == 2) return 1;
return fibonacci(iNum - 1) + fibonacci(iNum - 2);
}
public static long CallFibocacci(int n)
{
long sum = 0;
for(int i = 1;i <= n; ++i)
{
long ltemp = fibonacci(i);
sum += ltemp;
System.out.println(ltemp + ",");
}
return sum;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment