Click to See Complete Forum and Search --> : C++ help
nothing
08-07-2004, 01:32 AM
I am trying to solve this problem (http://acm.uva.es/p/v1/100.html) and here's what I got:
#include <iostream>
int main()
{
int i;
int j;
int n;
int cycle_length = 1;
while(std::cin >> i >> j){
std::cout << i << ' ' << j << ' ';
n = i;
while(n < j){
while(n > 1){
if(n % 2 != 0)
n = 3 * n + 1;
else
n /= 2;
}
i++;
n = i;
cycle_length++;
}
std::cout << cycle_length << '\n';
cycle_length = 1;
}
std::cin.sync();
std::cin.get();
return 0;
}
I gives me the wrong answers though and I can't find the error. Can somebody help me please? Thank you.
ScaryBinary
08-07-2004, 11:55 AM
Here are my comments after a quick look. I could be all washed up, so make sure what I'm saying makes sense!
1. You are supposed to be looking for integers between and including i and j. Your second while loop, though, is checking for n < j. Maybe this should be n <= j.
2. Unless I'm misunderstanding the problem, you need to find the maximum cycle length for all integers between and including i and j. I think you're computing this cycle length incorrectly....what you'd have to do is move your cycle_length++ into your while(n > 1) loop. This will give you the cycle length for a particular integer n. Then you need to store this cycle_length in something like max_cycle_length. Then, for the next integer you're checking, if your computed cycle_length is greater than the one stored, update max_cycle_length to the computed cycle_length. That way your computingn the cycle length for each integer, and saving the biggest one.
Hope this makes sense. I'll try to mod your code and see if I can get the proper results.
ScaryBinary
08-07-2004, 12:01 PM
I have it working. I'd hate to post the code and spoil the "fun" for you, but if you need it, I gots it.
On a side note, my first comment may or may not be applicable....:D
nothing
08-07-2004, 03:21 PM
I will try it on my own and post the result later. Thanks for the tips :D
nothing
08-08-2004, 04:53 PM
Think I got it.
#include <iostream>
int main()
{
int i;
int j;
int n;
int cycle_length = 1;
int max_cycle_length = 0;
while(std::cin >> i >> j){
std::cout << i << ' ' << j << ' ';
while(i <= j){
n = i;
while(n != 1){
if(n % 2 != 0)
n = 3 * n + 1;
else
n /= 2;
cycle_length++;
}
if(cycle_length > max_cycle_length)
max_cycle_length = cycle_length;
i++;
cycle_length = 1;
}
std::cout << max_cycle_length << '\n';
max_cycle_length = 0;
}
std::cin.sync();
std::cin.get();
return 0;
}
ScaryBinary
08-08-2004, 05:15 PM
Rock On! :t
nothing
08-08-2004, 06:16 PM
There's a problem: I submitted my code to their website and they said it is wrong. I think we misunderstood the problem :(
ScaryBinary
08-08-2004, 06:56 PM
:eek:
No way! I got the same results they did on the website you provided!
No, my friend, I think they're wrong. :D
SysOpt.com
Copyright Internet.com Inc. All Rights Reserved.