This question already has answers here:
Recursion in C. Making a non-recursive function a recursive one
(3 answers)
Closed 10 years ago.
Everything compiles and runs perfectly for my program. I had to write a recursive GCD function. I used two functions however, gcdRecursive and gcd. Can I condense this code into a single function so I do not need the gcd function within my code below? Or is my code correct as it is and the two functions are both needed.
void gcdRecursive(int *x, int *y, int i){
if (i >= 1) {
if (*x % i == 0 && *y % i == 0) {
printf("The GCD of %d and %d is %d", *x, *y, i);
}
else {
gcdRecursive(x, y, i - 1);
}
}
}
void gcd(int *x, int *y){
getValuesForGCD(x, y);
gcdRecursive(x, y, *x);
}
Yes it is correct but it is by far sub-optimal.
EDIT: try to use this:
if (x > y)
gcd(x,y) = gcd(y, x);
if (y % x == 0)
gcd(x, y) = x;
else
gcd(x, y) = gcd(x, y%x)
A more compact form could be
int getGcd(int num1, int num2)
{
int remainder;
if(num2 != 0)
remainder = (num1 % num2);
return ((num2 == 0) ? num1: getGcd(num2, remainder));
}
Related
I am trying to CALCULATE the Exponential function of x with recursion function .the Exponential function is calculated from this equation .
I divided the Exponential function for two part the first part which is Fracture
(i calculated it with the recursion function at the bottom and then put this part in while loop at the main function to find the sum from 0 to N
AS i am beginner in c and my English is not perfect please explain my Mistake in a SIMPLE WAY .
THANK IN ADVANCE .....
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<math.h>
#include<conio.h>
double faktoriyel(double x,double N);
int main(){
double N, x, a;
double s = 0;
scanf("%lf", &x);
scanf("%lf", &N);
a = N;
do
{
s += faktoriyel(x, N);
--a;
}while (a > 0);
printf("\n%lf\n", s);
}
double faktoriyel(double x, double N)
{
if (N < 0)
return -1;
else if (N < 2)
return pow(x, N) / 1;
else
return (pow(x, N) / N * faktoriyel(x, N - 1));
}
Your base case is not right.
It should be
if(N == 0)
return 1;
Why because anything raised to the power 0 is one.So returning 0.
Your method is not proper way of using recursion.
Check this code.
#include <stdio.h>
int power(int n1, int n2);
int main()
{
int base, powerRaised, result;
`printf("Enter base number: ");`
`scanf("%d",&base);`
`printf("Enter power number(positive integer): ");`
`scanf("%d",&powerRaised);`
`result = power(base, powerRaised);`
`printf("%d^%d = %d", base, powerRaised, result);`
`return 0;`
}
int power(int base, int powerRaised)
{
if (powerRaised != 0)
`return (base*power(base, powerRaised-1));`
`else`
`return 1;`
}
I changed it a bit here:
double faktoriyel(double x,double N)
{
if (N == 0) return 1;
else return (x/N * faktoriyel(x,N-1));
}
why? because you wrote
return (pow(x, N) / N * faktoriyel(x, N - 1));
which results in caculating
(x^(N+(N-1)+.....+1))/(N!)
instead of x^N/N!.
that is because you recalculate x^N every call to the function
and then multiply it :
(x^N)(x^(N-1))....*1
and here:
do
{
s+=faktoriyel(x,N);
--N;
}while (N>=0);
instead of this:
do
{
s += faktoriyel(x, N);
--a;
}while (a > 0);
because you actually calculated
x^N/N! + x^N/N! +.....+x^N/N!
instead of :
x^N/N! + x^(N-1)/(N-1)! +.....+1;
decrementing 'a' does not decrement N, resulting
in an incorrect calculation of e^x.
it should work btw.
As far as I can tell the logic in this makes sense. Yet the output is incorrect and I can seem to make sense of it.
#include <stdio.h>
int gcd(int, int);
int main()
{
int n, m;
printf("enter two numbers");
scanf("%d%d", &n, &m);
printf("The gcd of %d and %d is: %d \n", n, m, gcd(n,m));
return 0;
}
int gcd(int x, int y)
{
while(x!=y){
if(x>y)
return (x-y,y);
else
return(x,y-x);
}
return x;
}
That's not a recursive implementation of gcd, the function is not calling itself and besides it's using a while loop. A truly recursive approach will look like this:
int gcd(int x, int y) {
if (y == 0)
return x;
else
return gcd(y, x % y);
}
Or a bit shorter:
int gcd(int x, int y) {
return y == 0 ? x : gcd(y, x % y);
}
The above implementation is based on the Euclidean algorithm, refer to this for more details.
return (x-y,y);
will simply return y. That code compiles, but probably does not what you expected.
A non-recursive Euclid GCD algorithm would look like this:
int gcd (int x, int y)
{
while (y != 0)
{
int r = x % y;
x = y;
y = r;
}
return x;
}
Compared with a recursive version :
int gcd (int x, int y)
{
return y == 0 ? x : gcd (y, x%y);
}
As always in these trivial examples, the recursive approach uses less source code but is inefficient.
Copies of x and y plus the return address are passed on the stack, while the linear version simply works with an intermediate variable r for the remainder of x / y.
Even if some compilers might be smart enough to detect the unnecessary recursion and optimize it away, I think it is useful to understand the inherent cost of recursive coding.
so I have to write a recursive algorithm for exponentiation and I have to use this to make the algorithm faster: and then I'd have to figure out how many time multiplication is happening. I wrote it, but I am not sure if I am right - also I need some help with figuring out the multiplication part.
#include <stdio.h>
#include <math.h>
double intpower(double x, int n)
{
double result;
if(n>1&&n%2!=0) {result=x*intpower(x,(n-1)/2)*intpower(x,(n-1)/2);}
if(n>1&&n%2==0) {result=intpower(x,n/2)*intpower(x,n/2);}
if(n==1) return x;
else return result;
}
int main()
{
int n;
double x,result;
printf("x\n");
scanf("%lf", &x);
printf("n\n");
scanf("%d", &n);
printf("result = %.2f\n", intpower(x,n));
return 0;
}
The inductive definitions are saying
If k is even, then x^k = [ x^(k/2) ] ^ 2
If k is odd, then x^k = x * [ x^(floor(k)/2) ] ^ 2
With these it's a bit easier to see how to arrange the recursion:
#include <stdio.h>
double int_pwr(double x, unsigned k)
{
if (k == 0) return 1;
if (k == 1) return x; // This line can be omitted.
double y = int_pwr(x, k/2);
return (k & 1) ? x * y * y : y * y;
}
int main(void)
{
double x;
unsigned k;
scanf("%lf%u", &x, &k);
printf("x^k=%lg\n", int_pwr(x, k));
return 0;
}
I've changed types to be a bit more logical and saved an exponential (in k) amount of work that the OP's solution does by making two recursive calls at each level.
As to the number of multiplications, it's pretty easy to see that if k's highest order bit is 2^p (i.e. at position p), then you'll need p multiplications for the repeated squarings. Another way of saying this is p = floor(log_2(k)). For example if k=4=2^2, you'll square the square to get the answer: 2 multiplications. Additionally you'll need q-1 more, where q is the number of 1's in k's binary rep. This is the number of times the check for "odd" will be true. I.e. if k = 5 (which has 2 bits that are 1's), you'll square the square and then multiply the result by x one more time. To summarize, the number of multiplications is p + q - 1 with p and q as defined above.
To figure out how many times multiplication is happening, you could count them in intpower().
static int count = 0;
double intpower(double x, int n) {
double result;
if(n>1&&n%2!=0) {result=x*intpower(x,(n-1)/2)*intpower(x,(n-1)/2); count += 2;}
if(n>1&&n%2==0) {result=intpower(x,n/2)*intpower(x,n/2); count++;}
if(n==1) return x;
else return result;
}
int main() {
int n;
double x,result;
printf("x\n");
scanf("%lf", &x);
printf("n\n");
scanf("%d", &n);
mcount = 0;
printf("result = %.2f\n", intpower(x,n));
printf("multiplcations = %d\n", mcount);
return 0;
}
Try this
double intpower(double x, int n)
{
if(n == 0) return 1;
if(n == 1) return x;
if(n%2!=0)
{
return x*intpower(x,(n-1));
}
else
{
x = intpower(x,n/2);
return x*x;
}
}
or you can reduce your function to one line
double intpower(double x, int n)
{
return n == 0 ? 1 : n%2 != 0 ? x*intpower( x, (n-1) ) : (x = intpower(x, n/2), x*x);
}
I am getting segmentation fault with the following program. I am trying to find out the GCD using recursive function. The code is:
#include<stdio.h>
int gcd(int a, int b)
{
int temp, g, c;
if(a>b)
{
c=a;
a=b;
b=c;
}
//printf("The values of a and b are: %d %d",a,b);
temp = a % b;
if(temp != 0)
{
g = gcd(b, temp);
return(g);
}
if(temp == 0)
g= b;
return g;
}
int main()
{
int a,b;
printf("Enter two numbers: \n");
scanf("%d %d", &a, &b);
printf("The GCD of two numbers you entered are: %d\n", gcd(a,b));
}
The problem that I found out is in swapping variables. If I am removing it then the code is working fine. Can anybody tell me where I am going wrong? I am trying to implement it using Euclidean algorithm. So no other method can be implemented.
if(a>b)
{
c=a;
a=b;
b=c;
}
temp = a % b;
The problem is here. First, you're making sure that b > a. Now, if b is greater than a, it's not difficult to prove that a % b == a. For instance, 2 % 5 = 2.
Just replace the last line with
temp = b % a;
or, even better, reverse the condition for swapping :
if(a < b)
Instead of swapping the variables at the GCD function,Find the max number and send it as a and min number as b in the main function itself.
int GCD(int a, int b)
{
if (b == 0)
return a;
else
return GCD(b, a % b);
}
The condition should be
if (a < b)
Because doing
// Pre-condition: a >= b
temp = a % b;
// Post-condition: temp < b or temp == 0.
then the call gcd(b, temp)
has: temp < b, b <= min(original a, original b)
And so gcd terminates (variant a + b getting smaller on every call).
i think there is no need for the if (a > b) test, just remove it. If a >= b, the code works just as you want; if not, the first recursive call just do the swap.
You really don't need to check for each step which is greater (a or b).
Use following function to calculate gcd of two numbers.
int gcd(int a ,int b){
if(a % b == 0)
return b;
return gcd(b,a%b);
}
That's it.
Why to complicate things that much? Use this:
int findgcd(int x,int y){
while(x!=y){
if(x>y)
return findgcd(x-y,y);
else
return findgcd(x,y-x);
}
return x;
}
gcd should be a recursive function. It should return void. It should take two positive integers and place the GCD in the third parameter.
Here is my coded gcd function. However, I realized that it is not a recursive function. How would I change this code so it is a recursive function?
void gcd(int *x, int *y) {
int i;
getValuesForGCD(x, y);
for (i = *x; i >= 1; i--)
{
if (*x % i == 0 && *y % i == 0)
{
printf("The GCD of %d and %d is %d", *x, *y, i);
break;
}
}
}
GCD is naturally defined as a recurrent formulae. It's straightforwardly transformed into a recursive function:
gcd(a, 0) = a
gcd(a, b) = gcd(b, a % b)
Write this in a C format and that's it.
int gcd(int a, int b) {
if (b == 0)
then return a
else return gcd(b, a % b);
}
You should notice that a and b must be non-negative number.
and the nice thing is, this is a tail-recursion, so it run as fast as non-recursive method.
Normally, people work to remove recursion, not introduce it.
If you want a literal conversion of your iterative algorithm to recursive, it would go like this:
void gcdrecursive(int *x, int *y, int i)
{
if (i >= 1) {
if (*x % i == 0 && *y % i == 0) {
printf("The GCD of %d and %d is %d", *x, *y, i);
} else {
gcdrecursive(x, y, i - 1);
}
}
}
void gcd(int *x, int *y) {
getValuesForGCD(x, y);
gcdrecursive(x, y, *x);
}
To convert an iterative solution to recursive, you convert each loop to a recursive function that performs one iteration of the loop, then calls itself recursively for the next iteration. Breaking the loop corresponds to stopping the recursion. In your example, the loop breaks for two reasons: Either the GCD is found or i reaches zero.
Note that this is not the best algorithm for gcd, but it takes the function you provided and converts it to recursive, as requested.