Hello, I need to solve the problem part1 and the extra practice part using C lan
ID: 3850795 • Letter: H
Question
Hello, I need to solve the problem part1 and the extra practice part using C language.
I just learned basic recursion so I hope the code isnt that hard.
PART 1.Calculating the cost of a task that takes many identical steps can be expressed as so:
f(x) = f(x-1) + g(x),
Where f(x) is the cost of doing a task with x steps, and g(x) is the cost of doing that particular step.
Say you have such a task with the following cost function:
f(x) = f(x-1) + 4x, where f(0) = 2 and f(1) = 5
Write a recursive function that calculates the total cost of such a task. Use the following prototype:
int costFunction(int num);
Where it takes a number of steps in the task and returns the final cost.
Extra Practice
Take the above code and replicate it using iteration (loops) instead of recursion. Can you see any patterns that arise?
What if part 2 didn’t include f(0), and f(1)? Could you still do the problem? Would you be missing information that is needed for the recursion to work?
Change part 2 such that g(x) = f(x-2). How would you go about solving the problem now?
Rewrite part 1 such that you can only use addition (no multiplication). This means you have to do extra recursive calls. How would you do it now?
Explanation / Answer
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
int func, func1, x;
int costFunction(int);
int g(int);
printf(" Enter Number:");
scanf("%d", &x);
func = costFunction(x);
func1 = g(x);
printf(" f(%d) = %d", x, func + func1);
return 0;
}
int costFunction(int num)
{
int f;
int g;
f = (num - 1);
return f;
}
int g(int num)
{
return (num - 2);
}
OUTPUT
Enter Number: 1
f(1) = -1
Enter Number:2
f(2) = 1
Enter Number:3
f(3) = 3
Enter Number:4
f(4) = 5
Enter Number:
f(5) = 7
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.