I have called the function like this,
decimal2binary(1, 4);
By mistake i have re defined the variable m in the definition section of the following function
void decimal2binary(int m, int n) {
int arr[n];
cout<<"m:"<<m<<endl;
for(int i=0;i<n;i++)
{
if(m==0)
{
arr[i]=0;
}
else
{
arr[i]=m%2;
int m=m/2;
cout<<"m:"<<m<<endl;
}
}
when i ran the code i got the output like this,
m:1
m:1184170
m:592085
m:296042
m:148021
why this duplicate variable m producing the strange value, something like 1184170..592085. please tell me the reason.
You defined another variable with the name m in the else block, which shadows the function argument m, its scope begins right after int m, and it's uninitialized in the expression m/2.
in statement int m=m/2; here m on right side contains new m having garbage value. if you replace line int m=m/2; with line int m;//=m/2; you will see that value is actually a garbage value of m that is 2368340 for 1st case you are dividing this value by 2 to get 1184170(m/2) into m(m)
You define another variable with same name m inside else block and you performing operation
int m =m/2;
so compiler this will treat local m not outsider m;
and its give value unpredictable because you not intialize it;
Variable int m inside else block is not initialised. It contains some garbage value. You are dividing the garbage value by 2. Now when we say, it's uninitialised, it means, it can contain any value within the range of int.
I think, what you would like to do instead is::
// Inside else block
int temp = m ; // Store the older m value here
int m = temp/2 ;
Or the easy way::
int temp = m/2 ;
Related
In the below code, if I use just factorial(n), it gives the correct output (120), but when I use factorial(factorial(n)), the result is 0. Could someone please explain what is going wrong?
int factorial(int);
int main()
{
int n = 5; // number of terms
cout<<endl<<"The factorial is:"<<factorial(factorial(n));
return 0;
}
int factorial(int x)
{
if(x==1)
return 1;
else
return x * factorial(x-1);
}
Your problem is that you're hitting integer overflow.
As you noted the factorial of 5 is 120.
So factorial(factorial(5)) is the same as factorial(120). As you can see you're not passing the factorial function as argument to the outer factorial. You're passing the result of the call to the inner factorial as argument to the outer factorial.
The code is equivalent to this :
int result = factorial(5); // result = 120
factorial(result); // factorial (120)
The problem is that the factorial of 120 is a really big number, a number of almost 200 digits
Now this is way bigger than what an int can store. Or even a long long unsigned int. You need specialized libraries to handle arbitrarily big numbers.
factorial(factorial(5));
is effectively evaluated as if were written
temp = factorial(5); factorial(temp);
Based in the fact that we know temp will be set to 120 (we were told the function works for argument 5), the question is what happens in factorial(120).
The answer is: it overflows the maximum value of an integer.
I really do not have any clue about how to solve this task, can someone please help?
Consider the following function definition:
void f(int i, int &j) {
j = i+1;
i = j*2;
j += i;
}
In the following code:
int x = 4, y = 7;
f(x, y);
What are the final values of x and y?
For starters you could just run the code... but otherwise we can try and predict the output.
For starters the function f has two parameters, i and j. The & Infront of the j means that the value of the function input is passed by reference (the value of the variable will be edited).
So now let's evaluate the function with inputs 4, 7. We get:
j = 4+1 = 5
i = 10
j += i, j = 15
Because the variable y was passed by reference, its value will become 15. The variable x was passed by value, so it doesn't get affected and thus stays as 4.
Simply just run the code.Anyway the output will be
x=4(because it is passed as pass by value ->any change will not affect the outside the function f)
y=15(because it is passed as pass by reference->any change will affect the outside the function f)
char name[4][20];
int count=0;
cout<<"Enter 4 name at most , one name per line:\n";
while(cin.getline(name[count++],20))
;
--count;
(rest of code is for printing if u need to see that too it's at the end)
when i Enter names more than 4 it still prints those names but how can that happen?
because the first dimension is 4 so how can it get more than four
printing part of code:
for(int i=0; i<count; i++)
{
cout<<i<<"="<<name[i]<<endl;
}
system("pause");
}
If I get it correctly, your are asking "why if the array is 4 I can fit 5?".
Unlike Pascal, where arrays boundaries are checked at runtime, C++ doens't do such thing.
Think about it. An array is just some pointer that is added the offset later.
Let's say that you've an array of 5 integers and you do this
int a[5];
a[3] = 3;
a[6] = 4;
Nothing is really wrong, because in the first assignment, the statement equals to a+12 and the second one a+24. You're just incrementing the pointer and unless you don't bother the OS, you could go on and potentially overwrite some other data.
So C++ will very unlikely say something if you cross the arrays boundaries.
This implies that you must always somehow know how big is the array, in your case by simply adding to the loop:
while(count < 4 && cin.getline(name[count++], 20));
You need to tell the while() loop when to stop.
Try this:
char name[4][20];
int count=0;
cout<<"Enter 4 name at most , one name per line:\n";
while(count < 4 && cin.getline(name[count++],20))
;
This is my first question here so be kind :-) I'm trying to make a recursive call here, but I get the following compiler error:
In file included from hw2.cpp:11:
number.h: In member function ‘std::string Number::get_bin()’:
number.h:60: error: no matching function for call to ‘Number::get_bin(int&)’
number.h:27: note: candidates are: std::string Number::get_bin()
string get_bin ()
{
bin = "";
printf("Value is %i\n",val);
if (val > 0)
{
int remainder = val;
printf("remainder is %i\n",remainder);
printf("numbits is %i\n",size);
for (int numbits = size-1;numbits>=0;numbits--)
{
//printf("2 raised to the %i is %i\n",numbits,int(pow(2,numbits)));
printf("is %i less than or equal to %i\n",int(pow(2,numbits)),remainder);
if (int (pow(2,numbits))<=remainder)
{
bin+="1";
remainder -= int(pow(2,numbits));
printf("Remainder set to equal %i\n",remainder);
}
else
{
bin+= "0";
}
}
return bin;
}
else
{
int twoscompliment = val + int(pow(2,size));
return get_bin(twoscompliment);
}
Any thoughts? I know get_bin works for positive numbers.
In the last line you are calling get_bin() with an integer reference argument, but there are no formal parameters in the function signature.
string get_bin ()
return get_bin(twoscompliment);
These are mutually incompatible. I don't see how you can say that code works for positive numbers since it's not even compiling.
You probably need to change the first line to something like:
string get_bin (int x)
but, since you don't actually use the argument, you may have other problems.
If you're using global or object-level variables to do this work, recursion is not going to work, since they different levels will be stepping on each other's feet (unless you do your own stack).
One of the beauties of recursion is that your code can be small and elegant but using local variables is vital to ensure your data is level-specific.
By way of example, examine the following (badly written) pseudo-code:
global product
def factorial (n):
if n == 1:
return 1
product = factorial (n-1)
return n * product
Now that won't work for factorial (7) since product will be corrupted by lower levels. However, something like:
def factorial (n):
local product
if n == 1:
return 1
product = factorial (n-1)
return n * product
will work just fine as each level gets its own copy of product to play with. Of course:
def factorial (n):
if n == 1:
return 1
return n * factorial (n-1)
would be even better.
The function is defined to take no arguments, yet you pass an int.
It looks like you're accessing a global or member variable val. That should probably be converted into the argument.
string get_bin ( int val )
Since you have not declared bin and val in the function I guess they are global.
Now you define the function get_bin() to return a string and not accept anything. But in the recursive call you are passing it an int. Since you want to pass twoscompliment as val for the recursive call you can do:
int twoscompliment = val + int(pow(2,size));
val = twoscompliment; // assign twoscompliment to val
return get_bin();
I have this program
//h is our N
static int g=0;
int fun(int h){
if(h<=0){
g++;
return g;
}
return g+fun(h-1)+fun(h-4);
}
Is it possible to speed it up using dynamic programming?
I figured out that this function runs in O(2^n)
I am supposed to reduce the running time by dynamic programming, but do not understand the concept.
Just asking for a nudge in the right direction.
While I can't give an answer to your actual question, I am intrigued by something altogether different, namely the statement
return g+fun(h-1)+fun(n-4);
Obviously, your function has the side effect of changing the global static variable g. I am not 100% sure whether the return statement's expression actually evaluates in a clearly defined fashion, or whether the result might be undefined.
It might be a nice exercise to think about the order in which those function calls are executed, and how this affects g and thereby the function's result.
If we define that summation order in g+fun(h-1)+fun(n-4) is from left to rigth, than this is good defined problem. With that I get values for fun(n), n=1,...,15:
3, 6, 10, 15, 33, 74, 154, 295, 575, 1143, 2269, 4414, 8508, 16396, 31634
Return value of fun(n) is evaluated as sequence of summations with not-descending elements. Each summand is for one larger then previous (return g++;) or same as previous (return g+fun()+fun()). Execution sequence of return statements depend only of fun() input parameter. So, with g set to initial value != 0 we get same summands as with g=0, but every summand is larger for same initial value.
With that, fun(n) with initial g > 0 will return value that is g * number of executed return statements larger than with initial g = 0.
Define A(n) as number of executed return statements while executing fun(n), and G(n) number of executed return statement in if clause (same as number of g++ statement executions). For A and G holds:
A(n) = A(n-1) + A(n-4) + 1
G(n) = G(n-1) + G(n-4)
A(n) = 1 and G(n) = 1, for n <= 0
From these observations it can be seen that for n > 0 holds:
fun(n) = fun(n-1) + G(n-1) * A(n-4) + fun(n-4)
Simple python implementation:
def x( h ):
Rg = { -3:1, -2:1, -1:1, 0:1 }
Ra = { -3:1, -2:1, -1:1, 0:1 }
F = { -3:1, -2:1, -1:1, 0:1 }
for i in xrange( 1, h+1 ):
F[i] = F[i-1] + Rg[i-1]*Ra[i-4] + F[i-4]
print i, F[i]
Rg[i] = Rg[i-1] + Rg[i-4]
Ra[i] = Ra[i-1] + Ra[i-4] + 1
#stakx: for expression g+fun(h-1)+fun(h-4) we can't have evaluation order guaranty, especially not in C.
Yes , It's possible to use DP to speed it up and avoid using CPU stack, but I agree with stakx about the side effect of changing the global static variable g.
It's better to provide a mathematical expression because the recursive function above could give a different result depending on the order & count of calls.
OK. We start from fun (a serialized version where order of evaluation is forced).
int fun(int h){
if(h<=0){
g++;
return g;
}
int tmp1 = g;
int tmp2 = fun(h-1);
int tmp3 = fun(h-4);
return tmp1+tmp2+tmp3;
}
Let's focus on g and forget the current result of the function
Now it is easy to change the function to pass in g as a parameter and to return the new value of g as a result.
int gun(int h, int g0){
if(h<=0){
return g0+1;
}
int tmp1 = g0;
int tmp2 = gun(h-1, g0);
int tmp3 = gun(h-4, tmp2);
return tmp3;
}
What can be simplified into:
int gun(int h, int g0){
if(h<=0){
return g0+1;
}
return gun(h-4, gun(h-1, g0));
}
Now back to fun:
int fun2(int h, int g0){
if(h<=0){
return g0+1;
}
return g0+fun2(h-1, g0)+fun2(h-4, gun(h-1,g0));
}
fun2 does exactly the same thing as the initial fun, but now as we removed the side effect and the function only depends from it's parameter, we can memoize results (store already computed results in an array), which should speed-up the computing.
We can still simplify gun a bit. The g0 parameter is not really necessary, let's set it to 0.
int gun2(int h){
if(h<=0){
return 1;
}
return gun2(h-4) + gun2(h-1);
}
We may even define a fun3 with g0 parameter fixed to 0, henceforth a bit simpler, but it still has to call fun2. I do not see yet how to simplify further but it's probably possible.
int fun3(int h){
if(h<=0){
return 1;
}
return fun3(h-1)+fun2(h-4, gun2(h-1));
}