stuck in GCD of 2 numbers in C using recursion - c

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;
}

Related

The program needs to show the variable with greater first digit

The program needs to show an number which has a greater first digit, which works, only if the numbers of digits are the same on both variables. Try with these numbers 4506 29985, it should show 4506, but the program shows 29985, the program was written in C language.
#include <stdlib.h>
#include <stdio.h>
int disassembly1 (int a)
{
while (a>=10)
{
a /= 10;
}
return a;
}
int disassembly2 (int b)
{
while (b>=10)
{
b /= 10;
}
return b;
}
int main ()
{
int A1, B1, a, b;
printf("Int 2 numbers:\n");
scanf_s("%d %d", &A1, &B1);
a = A1;
b = B1;
disassembly1(A1);
disassembly2(B1);
if (a > b || ((a == b) && (A1 > B1)))
printf("%d\n", A1);
else
printf("%d\n", B1);
system("pause");
}
First of all, disassembly1 and disassembly2 are the same function and should not written twice.
Second and more important, the function disassembly returns the first digit, but you need to store it in a variable.
A working code (with a few changes):
#include <stdlib.h>
#include <stdio.h>
int disassembly(int a)
{
while (a>=10)
{
a /= 10;
}
return a;
}
int main()
{
int a, b, a_digit, b_digit;
printf("Int 2 numbers:\n");
scanf_s("%d %d", &a, &b);
a_digit = disassembly(a);
b_digit = disassembly(b);
if (a_digit > b_digit || ((a_digit == b_digit) && (a > b)))
printf("%d\n", a);
else
printf("%d\n", b);
system("pause");
return 0;
}
Also, the name disassembly does not match the function meaning. I would suggest to change it to something like get_first_digit.
Your code does not read the values returned from the functions, leaving variables a & b unchanged.
Change:
disassembly1(A1);
disassembly2(B1);
To:
a = disassembly1(A1);
b = disassembly2(B1);
Other suggestions:
define and use a single instance of function: int disassembly(int x); and call it twice.
a = disassembly(A1);
b = disassembly(B1);
Here is a much simpler version (this is matlab/octave, but can easily be ported to c)
a = 4506;
b = 29985;
isAbigger = floor(a/10^(floor(log10(a)))) > floor(b/10^(floor(log10(b))));

How to multiply 2 numbers using recursion

I'm trying to multiply (3, 6) and (9, 9) using recursion. However, the result printed is 18 and 45. I need to find out which part is wrong.
Here's my code:
#include <stdio.h>
int multiply (int, int);
int main()
{
int a, b, c;
a = 6; b = 3; c = multiply(a, b);
printf("%d\n", c);
a = 9; b = 9; c = multiply(a, b);
printf("%d\n", c);
return 0;
}
int multiply(int a, int b)
{
static int c = 0, i = 0;
if (i < a) {
c = c + b;
i++;
multiply(a, b);
}
return c;
}
The issue is that multiply's static variables persist from call to call, which throws the second calculation off. It is possible to bandage this wound, but it's better to address the underlying design problem that is compelling use of static variables in the first place. There is no need to artificially maintain state in the function using i (the number of additions to perform) and c (a product accumulator).
Given that multiplication is repeated addition of a b times, you can establish a base case of b == 0 and recursively add a, incrementing or decrementing b (depending on b's sign) until it reaches 0. The product accumulator c is replaced by the function return value and the number of multiplications i is represented by b.
Using this approach, each stack frame's state is naturally self-reliant.
#include <stdio.h>
int multiply(int a, int b) {
if (b > 0) {
return a + multiply(a, b - 1);
}
else if (b < 0) {
return -a + multiply(a, b + 1);
}
return 0;
}
int main() {
printf("%d\n", multiply(3, 6));
printf("%d\n", multiply(9, 9));
printf("%d\n", multiply(-6, 2));
printf("%d\n", multiply(6, -2));
printf("%d\n", multiply(-7, -3));
printf("%d\n", multiply(0, 7));
printf("%d\n", multiply(7, 0));
printf("%d\n", multiply(0, 0));
return 0;
}
Output:
18
81
-12
-12
21
0
0
0
As a final note, I recommend following proper code style. Minifying your code and using single-character variable names only makes debugging more difficult (someone has since de-minified the original code in an edit).
Both c and i need to be reset to zero on each [outer] call to multiply [as others have mentioned] because a function scope static variable is only initialized once.
There is no way to do this because the static variables are at multiply function scope (i.e. how does main access/reset them?). They would need to be moved to global/file scope.
Adding a helper function and moving the variables to global scope will do it:
#include <stdio.h>
int multiply(int, int);
int
main()
{
int a,
b,
c;
a = 6;
b = 3;
c = multiply(a, b);
printf("%d\n", c);
a = 9;
b = 9;
c = multiply(a, b);
printf("%d\n", c);
return 0;
}
static int c, i;
int
mul(int a, int b)
{
if (i < a) {
c = c + b;
i++;
mul(a, b);
}
return c;
}
int
multiply(int a, int b)
{
i = 0;
c = 0;
return mul(a,b);
}
Try resetting your static variables before second call to multiply or do without them
int multiply(int a, int b) {
If (a==0)
return 1;
else if (a>0)
return b+multiply(a-1, b);
else
return - 1*multiply(-1*a, b); }

How to get a recursive algorithm (C) to print steps?

Trying to work out how to get this code to print out its iterations as it runs for form checking. New to C and just trying to get my head around it while I work on things I already know (should know anyway) how they work. Recursive Euclidean Algorithm here.
int gcd(int a, int b)
{
if (b == 0) return a;
else return gcd(b , a%b);
}
try the following
int gcd(int a, int b)
{
if (b == 0)
{
printf("%d\n",a);
return a;
}
else
{
printf("%d\n",b);
return gcd(b , a%b);
}
}

Recursion in C. Making a non-recursive function a recursive one

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.

Given two int numbers A and B. How to find next multiple of B that is not less than A?

Suppose you input A = 15, B = 6, The answer is 18. What algorithm do I need?
This is what I try, but it doesn't work:
#include <stdio.h>
int main() {
int a, b;
scanf("%d %d", &a, &b);
for ( ; a % b != 0; a++ ) {
if ( a % b == 0 ) {
printf("%d\n", a);
return a;
}
}
return 0;
}
I get infinite loop.
The question (now) asks for:
The next multiple of b that is not less than a?
Using your notation of a and b, you can write it directly like this:
int NextMultipleUp(int a, int b)
{
int r = a % b;
if (r == 0)
return a;
else
return a + b - r;
}
The question originally asked for
The next multiple of a that is not greater than b
And for that the answer is
int NextMultipleDown(int a, int b)
{
return b - b % a;
}
This was the answer for which the original comments applied to.
return (((a-1) / b )+1) * b;
Always returns a multiple of b. Increment the integer dividend to get a multiple that is larger than the original a - subtract one from the original, because we want 'not less than' rather than 'greater than' a
I think that you want a do - while iterative loop, so I will give an alternative answer.
How to find next multiple of B that is not less than A?
Obviously this code is slower than David's.
int main ( void ){
int a, b, c;
long int result;
scanf("%d %d", &a, &b);
c = 0;
do {
result = b * c;
c++;
} while ( result < a );
printf( " The number is: %d \n", result );
}
int nextMultiple(int a,int b)
{
if(a%b == 0) return a;
return a+(b-(a%b));
}
so if a=15 b=6
the ans is
=15+(6-(15%6))
=15+(6-(3))
=15+3
=18

Resources