I'm diving into C++ and after going through some the tutorials on CProgramming.com, I saw a challenge to make a program factor a number using recursion. So I had to do it. The program through each instance finds the right factor and the right number of loops, but and the end when I print the linked list out it's all the last value I found. I feel like I'm close on this and need some help.
Big thanks in advance!
Code:
// class1.cpp: implementation of the class1 class.
//
//////////////////////////////////////////////////////////////////////
#include "class1.h"
#include "iostream.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
class1::class1()
{
}
class1::~class1()
{
}
struct fact {
int val;
fact *next;
};
void GO(int *srcNum, fact *srcFact) {
bool chgsrc;
fact *tmpFact;
tmpFact=new fact;
srcFact->next=new fact;
srcFact=srcFact->next;
srcFact->next=0;
srcFact->val=0;
chgsrc = 1;
if (*srcNum != 1) {
if (*srcNum % 2 == 0) {
srcFact->val=2;
if (chgsrc) {
*srcNum=*srcNum / 2;
cout<<"- "<<*srcNum<<endl;
cout<<srcFact->val<<endl;
cout<<srcFact<<endl;
//tmpFact=tmpRoot;
//if(tmpFact!=0)
//{
//while(tmpFact->next!=0)
//{
//cout<<tmpFact->val<<" - "<<tmpFact<<endl;
//tmpFact=tmpFact->next;
//}
//cout<<tmpFact->val<<endl;
//}
cout<<endl;
chgsrc = 0;
}
}
if (*srcNum % 3 == 0) {
srcFact->val=3;
if (chgsrc) {
*srcNum=*srcNum / 3;
cout<<"- "<<*srcNum<<endl;
cout<<srcFact->val<<endl;
cout<<srcFact<<endl;
cout<<endl;
chgsrc = 0;
}
}
if (*srcNum % 5 == 0) {
srcFact->val=5;
if (chgsrc) {
*srcNum=*srcNum / 5;
cout<<"- "<<*srcNum<<endl;
cout<<srcFact->val<<endl;
cout<<srcFact<<endl;
cout<<endl;
chgsrc = 0;
}
}
if (*srcNum % 7 == 0) {
srcFact->val=7;
if (chgsrc) {
*srcNum=*srcNum / 7;
cout<<"- "<<*srcNum<<endl;
cout<<srcFact->val<<endl;
cout<<srcFact<<endl;
cout<<endl;
chgsrc = 0;
}
}
}
if (srcFact->val != 0) {
GO(srcNum, srcFact->next);
} else {
//srcFact->val = *srcNum;
}
};
int main() {
fact *root;
fact *nxtFact;
int numtochk;
numtochk = 30;
nxtFact = new fact;
root=new fact;
root->next=0;
root->val=1; //Make this 1 because a factorial is atleast that number times 1.
nxtFact = root;
GO(&numtochk, nxtFact);
//NOW I WANT TO SEE ALL MY VALUES
nxtFact=root; //Lets go back to the beginning
if(nxtFact!=0)
{
while(nxtFact->next!=0)
{
cout<<nxtFact->val<<" - "<<nxtFact<<endl;
nxtFact=nxtFact->next;
}
cout<<nxtFact->val<<endl;
}
return 0;
}