Multiplying using only recursive functions and incrementation in C - c

So, for my assignment, I'm supposed to code a function that takes 2 unsigned arguments and outputs their product.
unsigned multiply( unsigned a, unsigned b );
For instance,
multiply(3, 4)
should return 12
The thing is, I'm not allowed to use +, -, /, *, or % operators. I'm only allowed to call functions, and increment/decrement with ++ and --.
I have another function already made to add 2 arguments:
unsigned add(unsigned a, unsigned b)
{
if (a > 0)
add(--a, ++b);
else return(b);
}
and I'm allowed to call this, along with any helper functions I need.
I've spent the past 30 minutes trying out various permutations but I just cannot get the math right; the closest I've come is getting b to double itself a times, but that's not going to cut it. Any ideas?
Edit: Forgot to mention! For/while loops aren't allowed either

unsigned add(unsigned a, unsigned b){
if (a > 0)
return add(--a, ++b);
else
return b;
}
unsigned multiply( unsigned a, unsigned b ){
if( a > 0)
return add(b, multiply(--a, b));
else
return 0;
}

int multiply (int a, int b)
{
int result = 0;
for (int i = 0; i < a; i++) { //You repeat "a" times...
for (int j = 0; j < b; j++) { //...adding "b" to result.
result++;
}
}
return result;
}
Of course if recursivity is mandatory, this won't works.

i didn't compile it but i`m sure its working
mutiply(3, 4, 0)
int mutiply(int a, int b, int result) {
if(a > 0) {
for(int i=1;i<=b;i++)
result++
mutiply(--a, b, result);
} else return (result == 0 && a == 0) ? 0 : result;
}

Here is a tail-recursive solution that uses a helper function with an accumulator. This is essentially the same as the solution using nested for loops:
unsigned multiply(unsigned a, unsigned b)
{
return mult_helper(a, b, 0, a);
}
unsigned mult_helper(unsigned a, unsigned b, unsigned acc, unsigned reset)
{
if (b == 0)
return acc;
if (a > 0)
return mult_helper(--a, b, ++acc, reset);
return mult_helper(reset, --b, acc, reset);
}

Related

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

Declare two variables split by comma equals to?

long i, b = get();
equals to
long i;
long b = get();
or
long b = get();
long i = b;
?
I'm totally new to c
It is first option
long i;
long b = get();
You would find it out faster by trying then asking on SO.
It's called operator ,.
In this case both expressions are evaluated, but only second's value is returned.
int x = 5;
while (--x, x > 0)
{
printf("%d,", x);
}
has output
4,3,2,1,
This code is same as
--x;
while (x > 0)
{
printf("%d,", x);
--x;
}

How to combine 2 integers in order to get 1?

I searched about this but I didn't find a clear answer for this problem in C language.
Imagine that I have an int a = 123 and another int b = 456.
How do I combine them in order to get combine(a, b) == 123456?
You can multiply a by 10-to-the-power-of-N, where N is the number of digits in b, then add that number to b.
Less efficiently, you can convert both to strings, concatenate them, then parse that string into an integer.
In either case, there is a possibility of integer overflow.
If b is allowed to be negative, you will have to further define the desired result.
First find the number of digits in "b"
This can be done as follows:
int find_num_digits(int b)
{
int i = 0;
while (b > 0)
{
b = b/10;
i++;
}
return i;
}
Then do:
c = a*10^find_num_digits(b) + b;
"c" is the result.
You will have to make sure that "c" doesn't go out-of-bounds.
int combine(int a, int b) {
return 1000*a + b;
}
More generically:
int combine(int a, int b) {
if (b==0) return a;
return combine(a, b/10)*10+ b%10;
}

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

how does the pointer to the function affect the sort?

This is a simple bubble sort using a function pointer for ascending or descending. I don't understand how the return statement on the ascending/descending function affects the swap.
Maybe I'm reading the return statement wrong on ascending? Does it mean return b if it's less than a? Or does it mean return 0 or 1 if the statement is true? Could use some clarification. Thanks.
void bubble( int work[], const int size, int (*compare)(int a, int b)){
int pass; /* pass counter */
int count;
void swap(int *element1Ptr, int *element2Ptr);
for ( pass = 1 pass < size; pass++){
/* loop to control number of comparison per pass */
if ((*compare)(work[count], work[count+1])){
swap(&work[count], &work[count + 1]);
}
}
}
void swap ( int *element1Ptr, int *element2Ptr){
int hold;
hold = *element1Ptr;
*element1Ptr = *element2Ptr;
*element2Ptr = hold;
}
/* determine whether elements are out of order for an ascending order sort */
int ascending( int a, int b){
return b < a;
}
int descending( int a, int b){
return b > a
}
A return statement in C returns the expression given, casted to the return type of the function (if possible). In these cases, b < a and a < b are boolean expressions, which return 1 or 0.
In other terms, it essentially means the following, but more concise (for b < a):
if (b < a) {
return 1;
}
else {
return 0;
}
return b < a;
means: return 1 when b < a and 0 otherwise, i.e. the function returns the value of the boolean expression b < a.

Resources