#include <iostream>
usingnamespace std;
int num = 11;
unsignedlonglongint number = 22;
int Divisor()
{
int result;
result = number%num;
if (result == 0 && num < 21)
{
num+1;
Divisor();
if (num == 20 && result == 0)
{
return number;
}
}
elseif (result != 0)
{
number++;
Divisor();
}
}
int main ()
{
Divisor();
cout << endl << endl;
system ("PAUSE");
return 0;
}
When I rum my program, it encounters an error in line 10.
The error states:
Unhandled exception at 0x009213b9 in Problem1.exe: 0xC00000FD: Stack overflow.Overflow.
Can someone help me with this?
EDIT:
The use of num from 11 is because the double of all the numbers from 1 to 10, have their doubles in the remaining half. so if a number is divisible by all the numbers from 11 to 20, it will also be divisible by numbers from 1 to 10!
stack overflow means that you have way too much recursion. I be you could straiten this out into a loop though.. Also, there was a thread about this problem before: http://www.cplusplus.com/forum/beginner/43732/ you might find ideas there..
Ah! Understood.
So After correcting line 16 (I had intended num+=1), I re-compiled it. Now the program gives no result.
I think it can be done using loops, but I believe that I should be able to solve it recursively.
Is there something wrong in this algorithm?
Now the program gives no result.
Yes, where's the output of 'number'?
Since you doing it with global variables 'Divisor()' don't need to return anything.
I don't understand. I put it out of the function so that the recursion doesn't resets the values, thus creating an unending recursion.
So how should I give the result?
I simply tried putting up cout << number after line 34 of my code.
The number it displays is 42.
PS. If I remove the return statement, The compiler gives an error saying that Divisor needs to return something.
But seriously: currrently you're looking for a number that is divisible by just one of the numbers between 1 and 20. Line 14 says that as soon as the result is 0 go to the next number.
22 % 11 = 0 and the next try is 12 -> 24 % 12 = 0 .... 42 % 21 = 0 and so you'll find 42
It is not the number that is increasing, but only the number dividing them.
At least my intentions were:
1.It will take the number 21.
2.It will divide it by 11.Since remainder is not 0, it will go increase the number by 1.
3.The new number is 22. It will divide it by 11.
4.The remainder is 0, so it will increase the divisor by 1. Or divide the 22 by 12. Since the remainder is not 0, it will repeat the steps.(hence, recursion).
It will increase the number if (result!=0)(line 25).
In my opinion this one is easier to do with a little math knowledge and a calculator.
If the question is restated like this: "Find the LCM of the numbers 1-20", new ways to approach the problem are discovered.