Need to work correctly for negative numbers

Id like to be able to have the for loop in the function to work correctly for negative numbers in either input position. Write a function that accepts two input parameters, computes their product(the result of multiplication),and returns the result. You are not allowed to use the multiplication operator(*)for performing multiplication You must implement this as repeated addition in a loop, building up the answer in an accumulator variable.
Any help will be appreciated
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48

#include<iostream>
using namespace std;


int addition(int, int);


int main()
{
	int num1,	//to store first number
		num2,	//to store second number
		product = 0;	//to store multiplication

	   //read numbers
	cout << "Enter first number: ";
	cin >> num1;
	cout << "Enter second number: ";
	cin >> num2;

	//call function
	product = addition(num1, num2);

	//print multiplication
	cout << "The product of " << num1 << " and " << num2 << " is: " << product << endl << endl;

	system("pause");
	return 0;
}

//function definition
int addition(int a, int b)

{
	int result = 0;
	
	for (int counter = 0; counter < b; ++counter)
	{
		result = result + a;
	}
	return (result);
}





  
Last edited on
So you have a function that calculates the product called addition?

Well, you don't need to use a loop for that. Instead you can use the * operator.

 
return a * b;

This will work for both positive and negative values of a and b.
Sorry I should have made this clearer mybad Write a function that accepts two input parameters, computes their product(the result of multiplication),and returns the result. You are not allowed to use the multiplication operator(*)for performing multiplication You must implement this as repeated addition in a loop, building up the answer in an accumulator variable.
Last edited on
you have to figure out the true sign of a.
a little truth table:
a, b -> +
-a, b -> -
a,-b -> -
-a,-b ->+

if its +, do nothing. if its -, change a: a = -a;
and then change the loop a little:
for (int counter = 0; counter < abs(b); ++counter)

that should do it.



I get the for loop but I don't understand the rest is there a if/else in there or where would this fit in ?

if (a = +) do nothing

else if (a = -) a = -a ? how do you write this ?
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>

long long product( int a, int b )
{
    // zero multiplied by anything yields zero
    if( a==0 || b==0 ) return 0 ;

    // product of two negative numbers is positive
    else if( a<0 && b<0 ) return product( -a, -b ) ;

    // product of a negative number and a positive number is negative
    else if( a<0 ) return -product( -a, b ) ;
    else if( b<0 ) return -product( a, -b ) ;

    else // both a and b are positive
    {
        // make the larger number a and the smaller number b (swap them if needed)
        // (to reduce the number of iterations)
        if( a < b ) { const int temp = a ; a = b ; b = temp ; }

        // you must implement this as repeated addition in a loop
        long long result = a ;
        for( ; b > 1 ; --b ) result += a ;
        return result ;
    }
}

int main()
{
    for( int a : { -1000, -23, -1, 0, +1, +23, +1000 } )
    {
        for( int b : { -1000, -23, -1, 0, +1, +23, +1000 } )
        {
            std::cout << a << " * " << b << " == "
                      << product(a,b) << " == " << a*b << '\n' ;
        }
    }
}

http://coliru.stacked-crooked.com/a/b39551f8ca49f9af
I will look at doing the repeated sum reduction, but the quick brute force version I came up with was this. ^^ I did not flip the args if B > A (yet) as I want to figure out the reduction logic first.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int p(int a, int b)
{
  int r = 0;  
  int a2 = abs(a);
  int b2 = abs(b);  
  if( (a < 0 && b > 0) || (a>0 && b < 0))
	  a2 = -a2;
  if(a&&b)
  {
	for(int i = 0; i < b2; i++)
	  r += a2;
  }
  return r;	
}
The fast version. It can be tweaked, but anyone have a better core approach?
what it does is create a bit shifter, i, which is 1,2,4,8,... etc powers of 2.
it then keeps a running addition of b. that is, when i is 1, its b. when i = 2, its b+b. When i = 4, its b+b+b+b. and so on. the sum you want is the bits of b related to that sum, eg if b were 5, which in binary is 4+1, you want (b+b+b+b) + b. Or in the code, it adds the zeros too (faster than checking), so its (b+b+b+b) +0(2's bit is zero)+ b
just like doing integer powers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
long long p(long long a, long long b)
{
  long long r = 0;  
  long long zero = 0;  
  long long a2 =  abs(a);
  long long b2 = abs(b);   
  if( (a < 0 && b > 0) || (a>0 && b < 0))
	  a2 = -a2;  
  long long* t[2] = {&a2, &zero};
    for(long long i = 1; i <= 9223372036854775808ull && b2 >= i; i= i << 1)   	
	{		
	  r += t[((unsigned long long)b2&(unsigned long long)i)==0][0]; 
	  a2+=a2;	  
	}
  return r;	
}

int main()
{
   cout << p(50000,-50000)<< endl;  //does less than 64 additions.  I think 16 for this example
   cout << p(3,-5)<< endl;
   cout << p(-3,5)<< endl;
   cout << p(3,5)<< endl;
   cout << p(0,-5)<< endl;
   cout << p(4,0)<< endl;
}


See if you can understand this. I don't advise turning it in, but if you can see how to do this, you will be way ahead of the class.
Last edited on
Thanks jonnin but between you and JLBorges I got it to work! Thanks to both of you for all your help its very much appreciated !
Last edited on
Good! But do you see how 50000*50000 can be done in only 16 additions? I am not always very good at explaining things.
Last edited on
Thanks its a little bit beyond my scope now but I understand the beginning recursion.6 x 1 = 6
6 x 2 = 6 + (6 x 1)
6 x 3 = 6 + (6 x 2) = 6 + [6 + (6 x 1)] = 6 + 6 + 6
Wait till you see my exponent program without multiplication or pow
exponent works just like addition in terms of relating the bits of the power to the answer. Its almost the exact same code.
2 to the 5th power... break 5 into its bits, 4 and 1 bit are set, so its 2*1 (1s bit) * 2*2*0(2's bit is zero) * 2*2*2*2 (4's bit) ... exact same idea.
Using recursion to handle negative numbers and adding appropriate values of a*2n for multiplying positive numbers. This is similar to JLBorges's and Jonnin's solutions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>

int product(int a, int b)
{
    if (a < 0) return -product(-a, b);
    else if (b < 0) return -product(a, -b);
    else {			// both are positive
	int result=0;
	for (unsigned mask=1; mask; mask <<= 1) {
	    if (b & mask) {
		result += a;
	    }
	    a <<= 1;
	}
	return result;
    }
}

int main()
{
    int a,b;
    while (std::cin >> a >> b) {
	std::cout << a << " * " << b << " = " << product(a,b) << '\n';
    }
}

Topic archived. No new replies allowed.