Description: 菲波那契数大家可能都已经很熟悉了: f(1)=0; f(2)=1; f(n)=f(n-1)+f(n-2) n>2。 因此,当需要其除以某个数的余数时,不妨加一些处理就可以得到。 Input: 输入数据为一些整数对P、K,P(1<P<5000),表示菲波那契数的序号,K(1<=K<15)表示2的幂次方。遇到两个空格隔开的0时表示结束处理。 Output: 输出其第P个菲波那契数除以2的K次方的余数。 Sample Input: 6 2
20 10
0 0
Sample Output: 1
85
|
package 实验二;
import java.util.Scanner;
public class 菲波那契数的余数 {
public static void main(String args[]){
递推2 f=new 递推2();
LinkList L=new LinkList();
Scanner reader=new Scanner(System.in);
long P=reader.nextLong();
long K=reader.nextLong();
long p;
long k;
long sum;
while(P!=0&&K!=0){
if(P<=1 || P>=5000)
break;
if(K<1 || K>=15)
break;
p=f.F(P);
k=(long) Math.pow(2, K);
sum=p%k;
L.add(sum);
P=reader.nextLong();
K=reader.nextLong();
}
if(L.length!=0)
L.show();
}
static void show() {
}
}
class 递推2{
long F(long n){
if(n==1)
return 0;
else if(n==2)
return 1;
else{
long a1=0;
long a2=1;
long a3=0;
for(int i=2;i<n;i++) {
a3=a1+a2;
a1=a2;
a2=a3;
}
return a3;
}
}
}
class Node {
long data;
Node next;
Node(long data){
this.data=data;
}
Node(){}
}
class LinkList{
int length=0;
Node head=new Node();
Node current=head;
void add(long data) {
Node node=new Node(data);
length++;
if(length==1) {
head.next=node;
current=node;
node.next=null;
}
else {
current.next=node;
node.next=null;
}
}
void show() {
Node p=head.next;
while(p!=null){
System.out.println(p.data);
p=p.next;
}
}
}