Need a bit of help with recursive! (c++)
Favorites|Homepage
Subscriptions | sitemap
HOME > > Need a bit of help with recursive! (c++)

Need a bit of help with recursive! (c++)

[From: ] [author: ] [Date: 12-04-10] [Hit: ]
...Thats why we will end it at the very first time we see the value 1.The length of the sequence starting at N (and ending when it reaches 1 the first time), is just the number of numbers in the sequence.......
Don't post full answers.

Suppose we let N to represent any integer in the sequence. If N is equal to 1, the sequence is finished (there is no "next" integer). If N is even, then the next integer is N/2. If N is odd, the next integer is 3*N+1.

Notice that the sequence repeats infinitely if you go past 1: 1,4,2,1,4,2,1,... That's why we will end it at the very first time we see the value 1.

The length of the sequence starting at N (and ending when it reaches 1 the first time), is just the number of numbers in the sequence. For example, the sequence 4,2,1 has length 3. The sequence starting at 1 has length 1.

Write a recursive function that will take a positive integer N, and will return the length of the sequence starting at N. Your main program ask the user for an integer value, and verify that the user typed a positive number prior to caling your function.

-
I don't remember c++ exactly, so pseudo-code will have to do. I'll also skip the verification, that's obvious.

Pseudo-code:
function Length (n) =
i = 1 <-- counter variable

If n is integer and n > 1, then
{
if n mod 2 = 0 [n is even]
i = i+1;
Length(n/2);

else
i = i+1;
Length(3n+1);
}

else if n not integer or n < 1
return FAIL;

else (n = 1)
return i;
end function;


That should work. First check that if it's an integer and greater than 1, then if it's even increase the length by 1 and run the function again on n/2 (here's the recursion). If n is odd but not 1, then add one and re-run with 3n+1. If n is one we know that will result in an infinite series so just return i, which is 1. And if n isn't applicable (not an integer or less than 1), then return a failure message.

You don't want this function to take 0 because that would also result in an infinite series of zeros since 0 is even.


You might want to throw some flags in there in your coding program to make sure you don't end up with an infinite loop, although it shouldn't loop.


Good luck!

-
If you don't want to do the work, then you shouldn't sign up for the class.

-
just going to answer cus i need some points. but i hope u find the answer ur looking for:)
1
keywords: with,recursive,help,bit,Need,of,Need a bit of help with recursive! (c++)
New
Hot
© 2008-2010 http://www.science-mathematics.com . Program by zplan cms. Theme by wukong .