This is the simplest problem from a bigger question. The simplified question is finding the size of a dividing chain from a 4-number chain, starting by the first number of the 4-number chain. As I said, I focus on the simplest case, for example:
Input: chain: 1,2,3,4
Output: 3 (size of chain:1,2,4). (Another chains are "1,3" or "1,4", but we don't mention, because finding them is easy if we can show the simplest "1,2,4").
Input: chain: 3,4,5,7
Output: 1 (size of chain:3)
Here is my code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
#include<iostream>
using namespace std;
int result(int a[4], int &count, int &start);
int main(){
int a[4];
for (int i=0; i<4; i++){
cin>>a[i];
}//getting input
int count=1;
int start=0;
cout<<"result showed by function: "<<result(a,count,start)<<endl;
cout<<"the value of count: "<<count<<endl;
system("pause");
return(0);
}
int result(int a[4], int &count, int &start){
//cout<<"start: "<<start<<endl;
if (start==3) return count;
for (int i=start+1; i<4;i++){
if (a[i]%a[start] ==0){
count++;
//cout<<"a["<<i<<"]:"<<a[i]<<endl;
//cout<<"count: "<<count<<endl;
start =i;
break;
}
if (i==3) return count;//no remained appropriate value for the chain
}
result(a,count,start);
}
|
With the input chain: 1,2,3,4 , as you see, the value of "count" is 3, the right answer. But the result of function "result" is a strange value, even though it is returned by "count". The similar result happens with input chain: 3,4,5,7. Any one who can tell me the problem? Thanks.