First, yes it's HW - really tried but not sure of something so ill be happy if you will help me:)
I have this code:
void func(int A[], int start, int n)
{
int p = n/2;
if ( 1 < n )
{
func(A, start, p);
func(A, start + p, n-p);
for (i=0; i<n; i++)
cout << A[start+i];
}
}
func(A, 0, n);
I need to give this code a recusive formula.
What I did was - first recursion call is T(n/2).
Second - this is the problem! really confuse with adding the 'p'...is that
T(n/2) too??
Three - for is running on theta(n)
and the outside recursion call is T(n)...
Can you help me get to the final formula??
Thanks
If I read it right, you want the recurrence for the run time complexity.
For n > 1, you recur with parameter floor(n/2) and with parameter n-floor(n/2), and after that you output n items. Thus you have
T(n) = T(cost of first recursive call) + T(second rec. call) + extra work
which you should now bring into a form suitable to apply the master theorem.
This is either a trick question or you misread the question. What you have is a recursive formula. Do you need to switch this formula from C++ to more traditional math notation? Do need to find a non-recursive algorithm? In your answer to the question, what is T? The term formula does not really apply here because nothing gets computed. This is a void function that never modifies the given array. All that happens is some things elements from the array get put on the screen in some order.
I would start by tracing an example to understand what is going on.
Lets say A = {1,2,3,4} Then 'func(A, 0,4)' is:
tracing func(A,0,4) :
p = 2
func(A,0,2)
func(A,2,2)
cout << 1 2 3 4
tracing func(A,0,2) :
p = 1 //start=0; n=2
func(A,0,1)
func(A,1,1)
cout << 1 2
tracing func(A,2,2) :
p = 1 //start=2; n=2
func(A,2,1)
func(A,3,1)
cout << 3 4
tracing func(A,2,1) :
p = 0 //start=0; n=1
func(A,0,0)
func(A,0,1)
cout << 1
tracing func(A,3,1) :
p = 0 //start=3; n=1
func(A,3,0)
func(A,3,1)
cout << 3
tracing func(A,2,1) :
p = 0 //start=0; n=1
func(A,0,0)
func(A,0,1)
cout << 1
At this point I'm going to stop because this is your homework problem. You can finish it from here.
Related
I am extremely new to the coding world. I just have a basic question regarding this function that squares integers from 0-9. I understand most of what's going on until I get to
std::cout << i << " " << square << "\n";
i = i + 1;
I'm not too sure how that ends up causing the output to square the results in order from 0-9. Can someone explain the reasoning behind this line of code? Here is the code for this function.
#include <iostream>
int main() {
int i = 0;
int square = 0;
while ( i <= 9) {
square = i*i;
std::cout << i << " " << square << "\n";
i = i + 1;
}
return 0;
}
This code:
std::cout << i << " " << square << "\n";
i = i + 1;
Doesn't square anything. It is merely outputting the current square that has already been calculated, and then increments i for the next loop iteration.
The actual squaring happens here:
square = i*i;
So, the code starts at i=0, calculates square=0*0 and displays it, then sets i=1, calculates square=1*1 and displays it, then sets i=2, calculates square=2*2 and displays it, and so on until i exceeds 9, then the loop stops.
Lets start from beginning and what is happening, I will ignore first several lines and start at:
int i = 0;
int square = 0;
You see when you say int i; your compiler says I need to allocate bucket of memory to hold value for i. When you say i = 0 zero is put into that memory bucket. That is what is happening for square as well.
Now to loop
while ( i <= 9 ) {
square = i*i;
std::cout << i << " " << square << "\n";
i = i + 1;
}
So, lets ignore
square = i*i;
std::cout << i << " " << square << "\n";
for now we will come to it later.
So
while ( i <= 9 ) {
i = i + 1;
}
goes into the loop and gets value from i's bucket, adds 1 and puts new value into the i's bucket. So in first loop it will be i = 0 + 1, put 1 into i bucket. Second, i = 1 + 1 put 2 in, third i = 2 + 1 put 3.
So lets go back to square and its bucket.
square = i*i;
So first time we go into the loop i = 0 and square = 0 * 0 so compiler puts 0 into square's memory bucket. Next time it hits square i has been incremented to 1 so square = 1 * 1, thus compiler puts 1 into the bucket. Third time i is 2 so square = 2 * 2, and compiler puts 4 into the bucket. And so on till it i <= 9. When i hits 10 loop is not executed.
In comments you have stated that you do not know the difference between a math equation and an assignment statement. You are not alone.
I will try to explain, as an addition to existing answers, to provide a different angle.
First, two examples of math equations:
x = 1 +1
y+1 = x*2
To illustrate their meaning, let me point our that you first can determine that x is 2 and in a second step that y is 3.
Now examples of assignment statements.
x = 1 +1;
y = x*2;
The minor difference is the ; at the end, tipping you off that it is a program code line.
Here the first one looks pretty much the same as the first equation example. But for a C compiler this is different. It is a command, requesting that the program, when executing this line, assigns the value 2 to the variable x.
The second assingment statement I made similar to the second equation example, but importantly different, because the left side of = is not an expression, not something to calculate. The equation-turned-statement
y +1 = x*2;
does not work, the compiler will complain that it cannot assign a value (no problem with doing a little calculation on the right side) to an expression. It cannot assign the value 4 to the expression y+1.
This helps with your problem, because you need to understand that both lines
i = i + 1;
square = i*i;
are statements which, when executed (and only then) cause a change to the value of the variable in that line.
Your program starts off with the value 0 in the variable i. At some point it executes the first of the statements above, causing the value of i to change from 0 to 1. Later, when the same line is executed again, the value of i changes from 1 to 2. So the values of i change, loop iteration by loop iteration, to 2,3,4,5,6,7,8,9
The second assignment line causes the value of square to become the value of i, whatever it is during that loop iteration and multiplied by itself. I.e. it gets to be 4,9,16,25,36....
Outputting the value of square each time in the loop gets you the squares.
Since you state that you basically understand loops, I just mention that the loop ends when i is not lower or equal to 9 any more.
Now from the other point of view.
If you try to solve the equation
i = i + 1
for i, you should hear your math teacher groaning.
You can subtract i from both sides and get
0 = 1
The solution is "Don't try.", it is not an equation.
std::cout << i << " " << square << "\n"; prints every
number i next to its square, which is previously computed
(square = i*i;).
i = i + 1; increments i to compute the next square. It stops when i reaches 10.
The output will look like this:
0 0
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
So we have a while loop here, which run while i <= 9. The square of any number i is i * i.
while(i <=9){ //check the condition and then enter the body
//body
}
But we need a condition to get out of the loop, otherwise our program will enter into an infinite loop.
To ensure, we will exit from the loop we increase the value of i by 1.
so at first when i = 0 square = 0 * 0 = 0,now we increase the value of i i.e now i becomes one which still satisfies the condition to stay inside the loop , again it will calculate square = 1 * 1 until and unless the value of i remains less than or equal to 9.
Once the condition fails, the execution comes out of the loop.
In C++, I should write a program where the app detects which numbers are divisible by 3 from 1 till 10 and then multiply all of them and print the result. That means that I should multiply 3,6,9 and print only the result, which is 162, but I should do it by using a "While" loop, not just multiplying the 3 numbers with each other. How should I write the code of this? I attached my attempt to code the problem below. Thanks
#include <iostream>
using namespace std;
int main() {
int x, r;
int l;
x = 1;
r = 0;
while (x < 10 && x%3==0) {
r = (3 * x) + 3;
cout << r;
}
cin >> l;
}
Firstly your checking the condition x%3 == 0 brings you out of your while - loop right in the first iteration where x is 1. You need to check the condition inside the loop.
Since you wish to store your answer in variable r you must initialize it to 1 since the product of anything with 0 would give you 0.
Another important thing is you need to increment the value of x at each iteration i.e. to check if each number in the range of 1 to 10 is divisible by 3 or not .
int main()
{
int x, r;
int l;
x = 1;
r = 1;
while (x < 10)
{
if(x%3 == 0)
r = r*x ;
x = x + 1; //incrementing the value of x
}
cout<<r;
}
Lastly I have no idea why you have written the last cin>>l statement . Omit it if not required.
Ok so here are a few hints that hopefully help you solving this:
Your approach with two variables (x and r) outside the loop is a good starting point for this.
Like I wrote in the comments you should use *= instead of your formula (I still don't understand how it is related to the problem)
Don't check if x is dividable by 3 inside the while-check because it would lead to an too early breaking of the loop
You can delete your l variable because it has no affect at the moment ;)
Your output should also happen outside the loop, else it is done everytime the loop runs (in your case this would be 10 times)
I hope I can help ;)
EDIT: Forget about No.4. I didn't saw your comment about the non-closing console.
int main()
{
int result = 1; // "result" is better than "r"
for (int x=1; x < 10; ++x)
{
if (x%3 == 0)
result = result * x;
}
cout << result;
}
or the loop in short with some additional knowledge:
for (int x=3; x < 10; x += 3) // i know that 3 is dividable
result *= x;
or, as it is c++, and for learning purposes, you could do:
vector<int> values; // a container holding integers that will get the multiples of 3
for (int x=1; x < 10; ++x) // as usual
if ( ! x%3 ) // same as x%3 == 0
values.push_back(x); // put the newly found number in the container
// now use a function that multiplies all numbers of the container (1 is start value)
result = std::accumulate(values.begin(), values.end(), 1, multiplies<int>());
// so much fun, also get the sum (0 is the start value, no function needed as add is standard)
int sum = std::accumulate(values.begin(), values.end(), 0);
It's important to remember the difference between = and ==. = sets something to a value while == compares something to a value. You're on the right track with incrementing x and using x as a condition to check your range of numbers. When writing code I usually try and write a "pseudocode" in English to organize my steps and get my logic down. It's also wise to consider using variables that tell you what they are as opposed to just random letters. Imagine if you were coding a game and you just had letters as variables; it would be impossible to remember what is what. When you are first learning to code this really helps a lot. So with that in mind:
/*
- While x is less than 10
- check value to see if it's mod 3
- if it's mod 3 add it to a sum
- if not's mod 3 bump a counter
- After my condition is met
- print to screen pause screen
*/
Now if we flesh out that pseudocode a little more we'll get a skeletal structure.
int main()
{
int x=1//value we'll use as a counter
int sum=0//value we'll use as a sum to print out at the end
while(x<10)//condition we'll check against
{
if (x mod 3 is zero)
{
sum=x*1;
increment x
}
else
{
increment x
}
}
//screen output the sum the sum
//system pause or cin.get() use whatever your teacher gave you.
I've given you a lot to work with here you should be able to figure out what you need from this. Computer Science and programming is hard and will require a lot of work. It's important to develop good coding habits and form now as it will help you in the future. Coding is a skill like welding; the more you do it the better you'll get. I often refer to it as the "Blue Collar Science" because it's really a skillset and not just raw knowledge. It's not like studying history or Biology (minus Biology labs) because those require you to learn things and loosely apply them whereas programming requires you to actually build something. It's like welding or plumbing in my opinion.
Additionally when you come to sites like these try and read up how things should be posted and try and seek the "logic" behind the answer and come up with it on your own as opposed to asking for the answer. People will be more inclined to help you if they think you're working for something instead of asking for a handout (not saying you are, just some advice). Additionally take the attitude these guys give you with a grain of salt, Computer Scientists aren't known to be the worlds most personable people. =) Good luck.
Hello I have a homework question I am stuck in..any hint or tips would be appreciated. the questions is:
Write a single recursive function in C++ that takes as argument a positive integer n then print n, n-1, n-2,...3,2,1,2,3,...n. How many recursive call does your algorithm makes? What is the worst case running time of your algorithm?
I am stuck in the first part. writing a recursive function that prints n, n-1, n-2,...3,2,1,2,3,...n
so far I have:
print(int n)
{
if (n==0)
return;
cout<<n<<" ";
print(n-1);
return;
}
but this only prints from n to 1
I am lost about how I would print from 2 to n using just one parameter and recursively single function.
I tried this: which gives the correct output but has a loop and has two parameters:
p and z has the same value.
void print(int p,int z)
{
if (p==0)
{
for(int x=2;x<=z; x++)
cout<<x<<" ";
return;
}
else
cout<<p<<" ";
print(p-1,z);
return;
}
any hint or tips is much appreciated thank you.
so it is working now, but I am having trouble understanding how (question in comment):
void print(int n)
{
if (n==1){
cout<<n;
return;
}
else
cout<< n;
print(n-1); // how does it get passed this? to the line below?
cout<<n; // print(n-1) takes it back to the top?
return;
}
The output you want is mirrored, so you can have this series of steps:
print num
recursive step on num-1
print num again
That's the recursive case. Now you need an appropriate base case upon which to stop the recursion, which shouldn't be difficult.
Given the pseudocode:
recursive_print(n):
if n == 1:
print 1
return
print n
recursive_print(n-1)
print n
(If you prefer, just look at your solution instead).
Let's trace it. A dot will mark where we're up to in terms of printing.
. recursive_print(3) // Haven't printed anything
3 . recursive_print(2) 3 // Print the 3
3 2 . recursive_print(1) 2 3 //Print 2
3 2 1 . 2 3 // Print 1
3 2 1 2 . 3 // Print 2
3 2 1 2 3 . // Print 3
Each unrolling of the function gives us 2 numbers on opposite sides and we build down to the "1", then go back and print the rest of the numbers.
The "unrolling" is shown in this picture:
If you strip away the functions and leave yourself with a sequence of commands, you'll get:
print 3
print 2
print 1
print 2
print 3
where each indentation signifies a different function.
Simple solution for this:
Def fxn(n):
if n <= n:
if n > 0:
print(n)
fxn(n - 1)
print(n)
Def main():
Number = 6
fxn(Number)
Main()
If you struggle understanding how this works:
Basically, each time you call a function in a recursive problem, it isn't a loop. It's as if you were on the woods leaving a trail behind. Each time you call a function inside a function, it does its thing, then it goes right back to were you called it.
In other words, whenever you call a recursive function, once the newer attempt is done, it will go right back to were it used to be.
In loops, once each step is done, it is done, but in recursive functions you can do a lot with a lot less.
Printing before the recurse call in my code is the descension step, and once its descension finished, it will progresively unfold step by step, printing the ascension value and going back to the former recurse.
It seems way harder than it is, but it is really easy once you grasp it.
The answer is simpler than you think.
A recursive call is no different from a regular call. The only difference is that the function called is also the caller, so you need to make sure you don't call it forever (you already did that). Let's think about a regular call. If you have the following code snippet:
statement1
f();
statement2
The statement1 is executed, then f is called and does it's thing and then, after f finishes, statement2 is executed.
Now, let's think about your problem. I can see that your hard work on this question from the second program you've written, but forget about it, the first one is very close to the answer.
Let's think about what your function does. It prints all numbers from n to 0 and then from 0 to n. At the first step, you want to print n, then all the numbers from n-1 to 0 and from 0 to n-1, and print another n. See where it's going?
So, you have to do something like this:
print(n)
call f(n-1)
print(n)
I hope my explanation is clear enough.
This is more of hack -- using the std::stream rather than recursion...
void rec(int n) {
if (n==1) { cout << 1; return; }
cout << n;
rec(n-1);
cout << n;
}
int main() {
rec(3);
}
prints
32123
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.
I am new to C++ programming and I am a bit lost. Here is what I am suppose to do and my code. Any ideas on what to do?
Write a program that uses while loops to calculate the first n Fibonacci numbers. Recall from math the following definition of the Fibonacci sequence:
The Fibonacci numbers Fn are defined as follows. F0 is 1, F1 is 1 and Fi+2 = Fi + Fi+1 for i = 0, 1, 2, ... . In other words, each number is the sum of the previous two numbers. The first few Fibonacci numbers are 1, 1, 2, 3, 5, 8, and 13.
The program should prompt the user for n (the number of Fibonacci numbers) and print the result to the screen. If the user enters an invalid value for n (n <= 0), print an error message and ask the user to re-enter n (an input validation loop for n). This MUST be a loop, not an if statement like Lab 2.
The output should be similar to the following:
Enter the number of Fibonacci numbers to compute: 3
The first 3 Fibonacci numbers are:
1 1 2
#include <iostream>
using namespace std;
int main()
{
int f0 = 0, f1 = 1,f2= 2, i = 0, n;
cout << "Enter the number of Fibonacci numbers to compute: ";
cin >> n;
if ( n <= 0)
{
cout <<"Error: Enter a positive number: ";
return 1;
}
while ( i < n){
f2 = f0 + f1;
i++;
}
cout << "The first " << n << " Fibonacci numbers are: " << endl;
cin >> n;
return 0;
}
while ( i < n){
f2 = f0 + f1;
i++;
}
See this loop, this is where the problem is, since this is homework, i'll not tell exactly what the problem is, take a pen and paper, and start executing your statements, specially this loop, you'll find your error. Just a hint, Fibonacci number is the sum of previous two fibonacci numbers.
You got the f2=f0+f1 right. However, you should note that when you increment i, then f2 becomes f1 and f1 becomes f0.
If you name them like this, it would make more sense:
int f_i_minus_2 = 0, f_i_minus_1 = 1, f_i;
and you would have
f_i = f_i_minus_1+f_i_minus_2;
Now, imagine i is 3. You have written:
f[3] = f[2]+f[1]
When you increment i, you must have:
f[4] = f[3]+f[2]
That is f_i is put in the place of f_i_minus_1 and f_i_minus_1 is put in the place of f_i_minus_2.
(Look at this:
f[3] = f[2] + f[1]
| |
\_____ \____
\ \
f[4] = f[3] + f[2]
)
So you need two assignments after computing f_i:
f_i_minus_2 = f_i_minus_1;
f_i_minus_1 = f_i;
Note that I first changed f_i_minus_2 to f_i_minus_1 because the second assignment destroys the value of f_i_minus_1.
According to wikipedia, your definition is off. F0=0, F1=1, F2=1, F3=2, ...
http://en.wikipedia.org/wiki/Fibonacci_number
Assuming wikipedia is right your loop is basically
int i = 0, f, fprev;
while( i < n )
{
if( i == 0 )
{
f = 0;
fprev = 0;
}
else if( i == 1 )
{
f = 1;
}
else
{
int fnew = f + fprev;
fprev = f;
f = fnew;
}
i++;
}
As others have pointed out, since you never modify f0 and f1 in the
loop, f2 isn't going to depend on the number of times through the
loop. Since you have to output all of the numbers at the end anyway,
why not try keeping them in an array. I'd initialize the first two
values manually, then loop until I had enough values.
(This can be done quite nicely using the STL:
// After having read n...
std::vector<int> results( 2, 1 );
while ( results.size() < n )
results.push_back( *(results.end() - 1) + *(results.end() - 2));
I'm not sure that this is what your instructor is looking for, however.
I rather suspect that he wants you to to some indexing yourself. Just
remember that if you initialize the first two values manually, your
index must start at 2, not at 0.)
Another thing: the specification you post says that you should loop if
the user enters an illegal value. This is actually a little tricky: if
the user enters something that isn't an int (say "abc"), then 1)
std::cin will remain in error state (and all further input will fail)
until cleared (by calling std::cin.clear()), and the illegal
characters will not be extracted from the stream, so your next attempt
will fail until you remove them. (I'd suggest >>ing into an
std::string for this; that will remove everything until the next white
space.) And don't ever access the variable you >>ed into until
you've checked the stream for failure—if the input fails. If the
input fails, the variable being input is not modified. If, as here, you
haven't initialized it, then anything can happen.
Finally (and I'm sure this goes beyond your assignment), you really do
need to do something to check for overflow. Beyond a certain point,
your output will become more or less random; it's better to stop and
output that you're giving up in this case.
If you are interested, there are better ways to calculate it.