先帖代码,这是我自己用链表写的,已经测试通过了:
程序代码:
#include<iostream>
class Node
{
public:
Node();
Node(int numValue,Node *nextNodeValue);
~Node();
void setNum(int numValue){num=numValue;}
void setNextNode(Node *nextNodeValue){nextNode=nextNodeValue;}
int getNum(){return num;}
Node* getNextNode(){return nextNode;}
private:
int num;
Node *nextNode;
};
Node::Node()
{
nextNode=NULL;
//num=0;
}
Node::Node(int numValue,Node *nextNodeValue)
{
num=numValue;
nextNode=nextNodeValue;
}
Node::~Node()
{
}
Node *checkCircle(Node *head,int tmp,Node *pFn_1);
using namespace std;
int main()
{
int a,b,n;
cin>>a>>b>>n;
Node *pFn=new Node();
Node *pFn_1=new Node(1,pFn);
Node *pFn_2=new Node(1,pFn_1);
Node *head=pFn_2;
while (a||b||n)
{
pFn_2=head;
pFn_1=pFn_2->getNextNode();
pFn=pFn_1->getNextNode();
pFn_2->setNum(1);
pFn_1->setNum(1);
int flag=0;
for(int i=2;i<n;i++)
{
int tmp=(a * (pFn_1->getNum()) + b * (pFn_2->getNum()))%7;
Node *tmpPNode=checkCircle(head,tmp,pFn_1);
if(tmpPNode)
{
pFn->setNum(tmp);
pFn->setNextNode(tmpPNode->getNextNode());
tmpPNode=tmpPNode->getNextNode();
int count=1;
while(tmpPNode!=pFn)
{
count++;
tmpPNode=tmpPNode->getNextNode();
}
//test code这段if根本不可能成立
if(count==0)
{
cout<<"test message."<<endl;
cout<<tmp<<endl;
flag=1;
break;
}
int j=(n-1-i)%count;
while(j--)
{
pFn=pFn->getNextNode();
}
cout<<pFn->getNum()<<endl;
flag=1;
break;
}
pFn->setNum(tmp);
pFn->setNextNode(NULL);
pFn_2=pFn_1;
pFn_1=pFn;
pFn=new Node();
pFn_1->setNextNode(pFn);
}
if(flag==0)
cout<<pFn_1->getNum()<<endl;
cin>>a>>b>>n;
}
return 0;
}
Node *checkCircle(Node *head,int tmp,Node *pFn_1)
{
Node *tmpHead=head;
while(tmpHead!=pFn_1)
{
if((tmpHead->getNum())==(pFn_1->getNum()))
{
Node *tmpP=tmpHead->getNextNode();
if((tmpP->getNum())==tmp)
{
return tmpP;
}
}
tmpHead=tmpHead->getNextNode();
}
return NULL;
}