Ok so I am having trouble understanding exactly how this program works:
#include <iostream>
using namespace std;
int getFibNumber(int fibIndex)
{
if(fibIndex < 2)
return fibIndex;
else
return getFibNumber(fibIndex - 1) + getFibNumber(fibIndex - 2);
}
int main(int argc, char** argv)
{
cout << "Enter 0-based index of desired Fibonacci number: ";
int index = 0;
cin >> index;
cout << "Fibonacci number is: " << getFibNumber(index) << endl;
return 0;
}
Specifically, what does "getFibNumber(...)" do when it reiterates(if that is the correct word)? I can't figure out what it does if the integer "fibIndex" that is passed in is greater than or equal to 2. Sorry to ask such a basic question, but I am really stumped by this and I feel like I'm missing something.
As everyone mentioned here, this is basically recursion.
Just to get a feel of how this program works, I have made the recursion tree with initial fibIndex as 5.
5 5 calls 4 and 3.
/ \
4 3 4 calls 3 and 2. 3 calls 2 and 1.
/ \ / \
3 2 2 1 1 is base case, returns 1.
/ \ / \ / \
2 1 1 0 1 0 2 is not base case. So calls 1 and 0.
/ \
1 0
This is called recursion. Instead of doing this with a loop it calls the function again, but with a different parameter. Eventually, the base condition will be true, and the function will return, causing the rest of the calls to return also. This can be a very powerful tool in the right situation.
Related
Problem
Finally, progress reached the Madoka family and she decided to play with her little sister in the sensational game Space Arrays.
The rules of the game are as follows:
Initially, a sequence a1,a2,…,aN is given.
The players alternate turns.
In each turn, the current player must choose an index i and increment ai, i.e. change ai to ai+1.
Afterwards, if there is no permutation p1,p2,…,pN of the integers 1
through N such that ai≤pi holds for each valid i, the current player
loses.
Otherwise, the game continues with the next turn.
Madoka is asking you to help her ― tell her if the first player (the player that plays in the first turn) or second player wins this game if both play optimally.
Input
The first line of the input contains a single integer T denoting the
number of test cases. The description of T test cases follows.
The first line of each test case contains a single integer N.
The second line contains N space-separated integers a1,a2,…,aN.
Output
For each test case, print a single line containing the string "First" if the first player wins or "Second" if the second player wins (without quotes).
Constraints
1≤T≤2⋅10^4
1≤N≤2⋅10^5
The sum of N over all test cases doesn't exceed 2⋅10^5
1≤ai≤N for each valid i
Subtasks
Subtask #1 (100 points): Original constraints
Example Input
4
4
1 2 3 3
4
1 1 3 3
5
1 2 2 1 5
3
2 2 3
Example Output
First
Second
Second
Second
Explanation
Example case 1:
If the first player increases the fourth element, the resulting sequence is (1,2,3,4).The second player loses after increasing any of the elements.
If the first player increases the second element, the resulting
sequence is (1,3,3,3) ,and he loses because there is no valid
permutation. For example if p=(2,1,4,3), the second element of a is
greater than the second element of p.
Time Limit : 1 Secs
Source limit : 50000 byte
Here is my code
#include <bits/stdc++.h>
using namespace std;
#define lli long long int
int main() {
// your code goes here
lli t;
cin >> t;
while(t--){
lli n;
cin >> n;
int arr;
int arrSum = 0;
for(lli i=0; i<n ;i++){
cin >> arr;
arrSum += arr;
}
lli turn = 0;
lli sum = (n*(n+1))/2;
turn = sum-arrSum;
if(turn < 0){
turn = 0;
}
if(turn%2 == 1){
cout << "First" << endl;
}
else{
cout << "Second" << endl;
}
}
return 0;
}
In your algorithm you don't check if first player initially loses without making a turn but the sum is lower than n*(n+1)/2, e.g. for input
1
5
1 1 2 5 5
The sum is 13.
5 * (5 + 1) / 2 - (1 + 1 + 2 + 5 + 5) == 1
But first player can't do anything and has lost before the first turn. Ssecond player wins.
Actual output from your code: First.
Expected output: Second
Another example is
1
5
1 1 4 4 4
with
5 * (5 + 1) / 2 - (1 + 1 + 4 + 4 + 4) == 1
In both cases your code returns that first player wins but actually second player wins without the game even starting.
Im trying to program a recursive function which will allow me to print each digit of a number on a separate line like this :
int decompose(int n){
if(n%10){
cout << n%10 << endl;
return decompose(n/10);
}
}
int main(int argc, char *argv[]){
decompose(2345);
}
OUTPUT
5
4
3
2
PROBLEM : I wanted to print on the other way
2
3
4
5
How to do that ?
void decompose(int n){
if (n>=10) //Call decompose if there are "more" digits in the number to print
decompose(n/10);
cout << n%10 << endl; //print the last digit of n
}
int main(int argc, char *argv[]){
decompose(2345);
}
Since you decompose first and print later in a number like 2345 the stack will look like this:
main()
decompose(2345)
decompose(234)
decompose(23)
decompose(2)
then as we start returning each call will print the last digit: 2 -> 3 ->4 ->5
NOTE: In your version you use the condition if(n%10){} this will be false whenever n is a multiple of 10. It means the versions with it will stop the moment a 0 digit is reached.
Try them with inputs such as 23450 or 23045
In your particular case you can just put the cout after the recursive calls and it will print in reverse order.
More generally, though, you can't always print directly in reverse order or it is not evident how to do it: in such cases you could append the output at each step to a vector of string and, once out of the function, print the vector in reverse order.
It's slightly less efficient and requires to keep in memory all the output at each step but, when these factors are negligible, it's easy to implement and understand.
I want a table of four values between 1 to 6.
I'm using: rand() % 6 + 1;
This should give values between 1 and 6.
Except if rand() generates the value 0.
I keep getting 7's. I don't want any 7's
What is the range of rand? How I prevent it from generation any 0 values?
Alternative solutions are quite welcome.
My teacher gave us the clue of using "random".
We use Borland C++ Builder 5 at school.
I am using Dev-C++ 5.3.0.3 at home.
I find there are a few differences to how they work, which I find strange..
I can't use random(), it gives me not declared in scope...
int main (){
int I;
int Fasit[3];
srand (time(NULL) );
for(I=0; I<4; I++) {
Fasit[I]=rand() % 6 + 1;
}
std::cout << Fasit[0] << " " << Fasit[1] << " " << Fasit[2] << " " << Fasit[3] << " ";
return 0;
}
Some values I get:
2 6 1 7
5 2 1 4
5 2 1 4
5 2 1 4
1 3 1 6
5 3 3 7
5 3 3 7
5 3 3 7
7 shouldn't be possible, should it?
PS: I know my print is ham fisted, I will make it a bit more elegant once the number generation works.
Consdier these lines:
int Fasit[3];
for(I=0; I<4; I++) {
Fasit[I]
You declare an array of three entries, which you write to four times.
Try your program again, but with:
int Fasit[4];
You only have 3 elements in Fasit[3]; When you write to Fasit[3], you are in the realm of undefined behavior, which in this case manifests it self with apparent contradiction.
Fasit[3] allows you to access only Fasit[0], Fasit[1], and Fasit[2].
Accessing Fasit[3], either for reading and writing, is undefined behavior. Your code is both writing and reading to Fasit[3] :-). The program is accessing the array out-of-bound. Fix it!
As to why 7 is printed, that is just coincidence. Note that Fasit[0-3] is always printed in the range 1-6 as you expected.
See also:
Array Index out of bound in C
Bounds checking
int Fasit[3];
You are creating an array of size 3, which can be accessed with indexes 0, 1 or 2 only.
You are writing and reading Fasit[3], which has an undefined behaviour. When a behaviour is undefined, you are bound to obtain weird results. This is it.
Let's say that I need to format the output of an array to display a fixed number of elements per line. How do I go about doing that using modulus operation?
Using C++, the code below works for displaying 6 elements per line but I have no idea how and why it works?
for ( count = 0 ; count < size ; count++)
{
cout << somearray[count];
if( count % 6 == 5) cout << endl;
}
What if I want to display 5 elements per line? How do i find the exact expression needed?
in C++ expression a % b returns remainder of division of a by b (if they are positive. For negative numbers sign of result is implementation defined). For example:
5 % 2 = 1
13 % 5 = 3
With this knowledge we can try to understand your code. Condition count % 6 == 5 means that newline will be written when remainder of division count by 6 is five. How often does that happen? Exactly 6 lines apart (excercise : write numbers 1..30 and underline the ones that satisfy this condition), starting at 6-th line (count = 5).
To get desired behaviour from your code, you should change condition to count % 5 == 4, what will give you newline every 5 lines, starting at 5-th line (count = 4).
Basically modulus Operator gives you remainder
simple Example in maths what's left over/remainder of 11 divided by 3? answer is 2
for same thing C++ has modulus operator ('%')
Basic code for explanation
#include <iostream>
using namespace std;
int main()
{
int num = 11;
cout << "remainder is " << (num % 3) << endl;
return 0;
}
Which will display
remainder is 2
It gives you the remainder of a division.
int c=11, d=5;
cout << (c/d) * d + c % d; // gives you the value of c
This JSFiddle project could help you to understand how modulus work:
http://jsfiddle.net/elazar170/7hhnagrj
The modulus function works something like this:
function modulus(x,y){
var m = Math.floor(x / y);
var r = m * y;
return x - r;
}
You can think of the modulus operator as giving you a remainder. count % 6 divides 6 out of count as many times as it can and gives you a remainder from 0 to 5 (These are all the possible remainders because you already divided out 6 as many times as you can). The elements of the array are all printed in the for loop, but every time the remainder is 5 (every 6th element), it outputs a newline character. This gives you 6 elements per line. For 5 elements per line, use
if (count % 5 == 4)
For the code below, could anyone please tell me why the function always returns "0" if the return value for the base case (n==0) is 0? I know in order to correct this function, I'd simply have to replace "return 0" with "return 1", however, I'm trying to understand why does it return 0 for the base case below.
Thanks for your help
int factorial(int n) {
if (n == 0) {
return 0;
} else {
return n * factorial(n-1);
}
}
Edit: Hopefully, the code below has no logical errors ...
#include<iostream>
#include<math.h>
using namespace std;
long double factorial (long double n) {
if (n==0) return 1;
if (n<0) return -fabs((n*factorial(n+1)));
return n*(factorial(n-1));
}
int main () {
long double n;
cout << "Enter a number: ";
cin >> n;
cout << "Factorial of " << n << " is " << factorial(n) <<endl;
return 0;
}
If you take a look at how the factorial is defined you'll find something like:
f(0) = 1
f(1) = 1
f(n) = f(n-1) * n
So your function does indeed return the wrong value for factorial(0). The recursion in this function basically works by decrementing n in every new function call of factorial.
Let's assume you call factorial(3). n would that with 3, the else branch will get executed as n does not equal zero. We follow the third rule of our definition an call factorial(2) (which is n-1) and multiply the result of it by n. Your function will step down until factorial(0) is called and returns 0 which then is a factor of all previous calculations, resulting in 3*2*1*0, and that equals to 0.
This code is simply wrong. No matter which n > 0 it gets as argument, every value is eventually multiplied with 0 and therefore factorial( n ) = 0 for all n > 0.
It returns zero since any number times zero is zero. You start with some number n, say n=5. As you go through the recursion you have:
n * factorial(n-1)
5 * factorial(5-1)
5 * 4 * factorial(4-1)
5 * 4 * 3 * factorial(3-1)
5 * 4 * 3 * 2 * factorial(2-1)
5 * 4 * 3 * 2 * 1 * factorial(1-1)
But factorial(1-1) is factorial(0) which returns 0, so you get :
5 * 4 * 3 * 2 * 1 * 0 = 0
For the code below, could anyone please tell me why the function returns "0" if the return value for the base case (n==0) is 0?
Someone chose to do that. You'd have to ask the author why they did that.
I know in order to correct this function, I'd simply have to replace "return 0" with "return 1", however, I'm trying to understand why does it return 0 for the base case below.
Likely because the person who wrote it thought 0! was equal to 0.
I don't get you question entirely but lets cal the function f(int n): int okey to make it shorter
for n = 0 it will return 0 becaulse thats what you told it to do right: if(n == 0) return 0;
for n + 1 youll get the folowing pattern:
f(n+1) ==> n * f(n) becaulse thats wat you told it to do otherwise right? and f again will evaluate.
so thats why youre function will return 0 in any case and if you alter the base case to 1 youll get:
For whatever n (bigger than or equal to 0), you multiply a lot of numbers down to factorial(0) which returns 0.
The result of
n*(n-1)*(n-2)*...*3*2*1*0
is a big fat 0
P.S. Besides not computing properly, the code has a major flaw. If you give it a negative number, you make it cry.