How to perform a multiplication using only additions and assignments? - c++

How do I change the following program, so that it performs the same Task, but using only additions and assignments?
I can only do max 27 additions, and the Output has to be generated in a single Input.
Loops and other control flow operations are not allowed
#include <iostream>
int main()
{
int a;
std::cout << "Enter number: ";
std::cin >> a;
std::cout << a*29 << std::endl;
return 0;
}

Another approach that requires 7 +:
int M1 = a; // 1a
int M2 = M1 + M1; // 2a
int M4 = M2 + M2; // 4a
int M8 = M4 + M4; // 8a
int M16 = M8 + M8; // 16a
int res = M16 + M8 + M4 + M1; // 29a
The result is constructed from the binary pattern of the multiplier, i.e. 29 decimal is 0001.1101 binary. So we need to add M16, M8, M4 and M1 (and exclude M2).

This is not general, and it cannot be, but to multiply just by 29 you can do this:
// x is input
int t = x; // x*1
x = x + x;
x = x + x;
t = t + x; // x*5
x = x + x;
t = t + x; // x*13
x = x + x;
t = t + x; // x*29
This is just unrolled binary multiplication, like the similar answers, but without naming the temporary results. The additions to t correspond to the set bits in 29.

This way you can do it with 21 additions.
#include <iostream>
int main()
{
int a;
std::cout << "Enter number: ";
std::cin >> a;
int b = (a+a+...+a) // 10 times
b = b + b;
b = b + (a + a + a ... + a ); // 9 times
std::cout << b << std::endl;
return 0;
}

Can you use an additional var?
b = a + a + a//3 times a
b = b + b + b//9 times a
b = b + b + b//27 times a
b = b + a + a//29 times a

Multiplication is just a repeated addition. Use a loop for this. Do you know how many times your loop should execute? Yes! So use a for loop.
So here is the plan:
Get input
Use a for loop to perform the addition
Output sum
Example:
// get input
int input;
std::cout << "Enter number: ";
std::cin >> input;
// use a for loop to perform the addition
int sum = 0;
for(int i = 0; i< 29; ++i)
sum += a;
// output result
std::cout << sum << std::endl;

,resRepetitive addition is multiplication -- mathematically
So repeat addition of a for n number of times. A simple for/while loop can do this
#include <iostream>
int main()
{
int a,i,temp=0;
std::cout << "Enter number: ";
std::cin >> a;
for(i=1;i<=29;i++)
temp+=a;//add a repeatedly for 'n' number of times. Here 29 as per your requirement. a*n
std::cout << temp <<std::endl;
return 0;
}
Without loop
int b=0,result=0;
b=a+a+a+a+a+a+a;\\adding for 7 times
result=b+b+b+b+a;\\4 times 7 (of a)= 28+a= 29 times (of a).
This involves 10 addition.

You can try this -
b = a + a + a + a + a + a + a + a + a + a + a + a + a + a + a; // equivalent to a*15
b += b -a;

If you are only allowed to use + and =, and are not allowed to cheat by introducing other variables, there is no way of doing this unless you indulge in a bit of undefined behaviour and allow yourself something of the form
... + (a += ...) + ...
where ... is any number of a +. The trick here is that (a += ...) changes the value of a part way through evaluation of the expression.
Tempting as it may be, alas this is not portable C++ since += and + are not sequencing points. On your classroom compiler, you might be able to get this to work.
See https://ideone.com/fC3fai, you can see that
(a + a + a + a + a + (a += a + a + a) + a + a + a + a + a)
does the job on that particular compiler (at the time of writing). (For what it's worth, it also does the correct thing in Java where the expression is well-defined).

You can add value multiple times:
int sum=0;
for(int i=0; i<multipler; i++){
sum+=a; //adds value of a to itself
}
return sum;
If you want to multiple only by 2 you can just shift left:
a = a << 1;

Related

C++ Simple Calculator (no if, Switch, Case, and its kind)

I tried to make Simple calculator. There are 3 inputs :
number 1
number 2
operators
The operator is selected using number :
1 = '+'
2 = '-'
3 = '*'
4 = '/'
Example :
Number1 = 1, number 2 = 1, operator = 1, then the equation goes 1 + 1 = 2.
I didn't know how to make this equation possible. Any help will be appreciated. Thanks!
*note : not using array or string, not using case, not using switch, not using if, while, for.
Here's my code, but it's not yet completed and I need to change the operator selector.
#include <iostream>
using namespace std;
int main (){
int a, b, c, hasil;
cout << "Masukkan Bilangan 1 : ";
cin >> a;
cout << "Masukkan Bilangan 2 : ";
cin >> b;
cout << "Masukkan Operator ['(0 = +)' , '(1 = -)' , '(2 = *)', '(3 = /)' ] : ";
cin >> c;
hasil = a + (c * -2 + 1 )* b;
cout << "Hasilnya = " << hasil;
}
You can use different functions for the different operators and then select them by using the "c" value as the index to a table of functions.
#include <iostream>
using namespace std;
typedef int (*OperatorFunction)(int a, int b);
static int OperatorPlus(int a, int b)
{
return a + b;
}
static int OperatorMinus(int a, int b)
{
return a - b;
}
static int OperatorMultiply(int a, int b)
{
return a * b;
}
static int OperatorDivide(int a, int b)
{
return a / b;
}
OperatorFunction operators[] = { OperatorPlus, OperatorMinus, OperatorMultiply, OperatorDivide };
int main()
{
int a, b, c, hasil;
cout << "Masukkan Bilangan 1 : ";
cin >> a;
cout << "Masukkan Bilangan 2 : ";
cin >> b;
cout << "Masukkan Operator ['(0 = +)' , '(1 = -)' , '(2 = *)', '(3 = /)' ] : ";
cin >> c;
hasil = operators[c](a, b);
cout << "Hasilnya = " << hasil << "\n";
}
you basically have to calculate all four of them at the same time (warning, "1+0" will then crash, because it will divide by zero during calculation, even if "+" operation was chosen), and filter out the unneeded ones.
To filter out unneeded ones you need to turn c into one of the four value sets:
c==1: [1, 0, 0, 0]
c==2: [0, 1, 0, 0]
c==3: [0, 0, 1, 0]
c==4: [0, 0, 0, 1]
Let's call those inner four values ci, i=1..4
c1 = ((c-2) * (c-3) * (c-4)) / -6;
c2 = ((c-1) * (c-3) * (c-4)) / 2;
c3 = ((c-1) * (c-2) * (c-4)) / -2;
c4 = ((c-1) * (c-2) * (c-3)) / 6;
Then:
result = c1 * (a+b) + c2 * (a-b) + c3 * (a*b) + c4 * (a/b);
This is "pure math" solution, without exploiting C++ bool implicit conversion to 0/1, which would be better in production code, but I think it's a bit "cheating" in this exercise, that's why I'm calculating the 0/1 coefficients without the bool conversions in such complex manner by using the polynomials.
Few updates, to steer away from "pure math" a bit toward something more practical.
unwanted division by zero solution: instead of (a/b) you can calculate (a/(b|(c4-1))) (for c4 being 0 or 1). This will make the divisor equal to -1 whenever the c4 is zero, so it will neutralise "division by zero" for inputs like "a = 1, b = 0, c = 1" (i.e. "1+0"), and the division by zero may happen only when operation "division" is selected and b == 0.
if you will flip ci values from [0, 1] to [0, -1] (just change sign of the fixed constants at the final normalizing division), and everything is int, then you can replace the ci multiplications in final formula with bitwise AND like: result = (c1 & (a+b)) + (c2 & (a-b)) + (c3 & (a*b)) + (c4 & (a/b)); - which will be marginally faster on modern CPU (and considerably faster on historic CPU). {then of course the division by zero fix has to be flipped too => b|(-1-c4)}
note: uh, I aimed for -1 for the division fix, thinking about making whole division going to 0 in unsigned math for most of the inputs, then I figured out this is signed int and overall it makes little sense, but I kept -1 as target value, while anything non-zero will work, even simple 1. And the bitwise AND works only on platforms where negative integers are implemented by two's complement logic, so -1 is full bitmask then (as you didn't specify platform, this may break on some weird ones... the original answer with multiplication will work even on those).
The only thing I can think of with this assignment is to make use of that in C++ there's an implicit conversion between boolean type and integer. To take advantage of it you can do :
#include <iostream>
using namespace std;
int main (){
int a, b, c, hasil;
cout << "Masukkan Bilangan 1 : ";
cin >> a;
cout << "Masukkan Bilangan 2 : ";
cin >> b;
cout << "Masukkan Operator ['(0 = +)' , '(1 = -)' , '(2 = *)', '(3 = /)' ] : ";
cin >> c;
// if your input is a=10, b=5, c=0 :
// a + b == 15
// !c == 1
// 15 * 1 == 15
// a - b == 5
// !(c - 1) == !(0 - 1) == 0
// 5 * 0 == 0
// and so on...
hasil = ((a + b) * !c) + ((a - b) * !(c - 1)) + ((a * b) * !(c - 2)) + ((a / b) * !(c - 3));
cout << "Hasilnya = " << hasil;
}
explanation :
If your c input is 0 and you're doing !c it will return 1 as a int representation of TRUE but then for each other value eg. 3 it will return 0 as a int representation of FALSE. This is then multiplied by the calculated value of each possible operator and return either calculated value or 0 ( because 0 * 99 == 0 ).
Try this online

Cannot include integers in a string in c++

When I try to make integers using the rand() function, I cannot include them in a string. These are the two codes that I have tried:
int x1, x2;
x1 = (rand() % 14 + 2);
x2 = (rand() % 14 + 2);
char c1 = char(x1);
char c2 = char(x2);
string Hand = {c1, c2};
cout << Hand << endl;
I don't get any errors with this one, but it doesn't run. This is the one I thought would be correct:
int c1, c2;
c1 = (rand() % 14 + 2);
c2 = (rand() % 14 + 2);
to_string(c1);
to_string(c2);
string Hand = {c1[0], c2[0]};
cout << Hand << endl;
Yet it isn't. This must be really simple. How is it done?
Note that c1 and c2 are not vectors, so c1[0] make no sense.
The to_string method returns a string, donĀ“t turns the argument into one. That said, the code could work better like this:
int c1, c2;
c1 = (rand() % 14 + 2);
c2 = (rand() % 14 + 2);
string Hand = {to_string(c2)[0], to_string(c1)[0]};
cout << Hand << endl;
Try something like this:
#include <iostream>
#include <stdlib.h> /* srand, rand */
#include <string>
#include <sstream>
using namespace std;
int main() {
// your code goes here
std::ostringstream ss;
int x1, x2;
x1 = (rand() % 14 + 2);
x2 = (rand() % 14 + 2);
ss << x1 << x2;
std::string Hand = ss.str();
cout << Hand << endl;
return 0;
}
C++ is statically typed language. std::to_string won't change the type... It returns the string.
As for the first code, you're dealing with non-printable characters.

C++ x doesnt loop increament

I have a task from my teacher,like :
x^2 + y^3 = z
x filled only with odd
y filled only with even
#include <stdio.h>
#include <string>
#include <iostream>
using namespace std;
int x,y,z;
int main(){
for (x=1;x<=20;x++){
if ((x%2==1)&&(y%2==0)){
for (y=1;y<=20;y++){
if ((x%2==1)&&(y%2==0)){
z = (x*x) + (y*y*y);
cout << "x^2 + y^3 =" <<z <<"\n";
}
}
}
}
}
I try to make my own code like above ,but the only one loop is Y , x stand still with 1.
I want to make x to be looping too. What should i do?
My output expectation would be like :
1^2 + 2^3 = 9
3^2 + 4^3 = 71
5^2 + 6^3 = 241
7^2 + 8^3 = 561
9^2 + 10^3 = 1081
11^2 + 12^3 = 1849
13^2 + 14^3 = 2913
15^2 + 16^3 = 4321
17^2 + 18^3 = 6121
19^2 + 20^3 = 8361
PS. Im sorry with my bad english :D
This is what you have:
int main(){
for (x=1;x<=20;x++){
if ((x%2==1)&&(y%2==0)){
for (y=1;y<=20;y++){
if ((x%2==1)&&(y%2==0)){
z = (x*x) + (y*y*y);
cout << "x^2 + y^3 =" <<z <<"\n";
}
}
}
}
}
The problem is the first if ((x%2==1)&&(y%2==0)){ check.
After the inner for loop is completed, the value of y will be 21. Hence, the above conditional evaluates to false no matter that the value of x is. As a consequence, the inner for loop is executed only once. You need to remove that first if statement.
int main(){
for (x=1;x<=20;x++){
for (y=1;y<=20;y++){
if ((x%2==1)&&(y%2==0)){
z = (x*x) + (y*y*y);
cout << "x^2 + y^3 =" <<z <<"\n";
}
}
}
}
Update, in response to OP's comment
Looks like you need much simpler code.
int main(){
// Start with x = 1 and increment x by 2. It will be always be odd
for ( x = 1; x <= 20; x += 2 ){
// No need to create another loop. y is simply x+1
// Since x is odd, y will be even.
y = x+1;
// Compute the result and print it.
z = (x*x) + (y*y*y);
cout << "x^2 + y^3 =" << z <<"\n";
}
}
Because y = 21 after the inside y loop.So the x loop will not be executed after . Hope it helpful.

Program to display a sum in C++?

I was given a task to write a program that displays:
I coded this:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a, n = 1, f = 1;
float s = 0;
cin >> a;
while(n <= a)
{
f = f * n;
s += 1 / (float)f;
n = n + 1;
}
cout << s;
getch();
}
So this displays -
s = 1 + 1/2! + 1/3! + 1/4! .... + 1/a!, including odd and even factorials.
For the past two hours I am trying to figure out how can I modify this code so that it displays the desired result. But I couldn't figure it out yet.
Question:
What changes should I make to my code?
You need to accumulate the sum while checking the counter n and only calculate the even factorials:
int n;
double sum = 1;
cin >> n;
for(int i = 2; i < n; ++i{
if(i % 2 == 0) sum += 1 / factorial(i);
}
In your code:
while(n <= a)
{
f = f * n;
// checks if n is even;
// n even if the remainder of the division by 2 is zero
if(n % 2 == 0){
s += 1 / (float)f;
}
n = n + 1;
}
12! is the largest value that fits in an 32 bit integer. You should use double for all the numbers. For even factorials, starting with f = 1 (0!), f = f * (n-1) * n, where n = 2, 4, 6, 8, ... .
You have almost everything you need in place (assuming you don't want to make design changes based on the issues brought up in the comments).
All you need to change is what you multiply f by in each step. To build up n! you are multiplying by n in each step. To build up (2n)! you would multiply by 2*n*(2*n-1)
Edit: Your second theory about what the instructor wants would need only slightly more of a change. Your inner loop could be replaced by
while(n < a)
{
f = f * n * (n+1);
s += 1 / f;
n = n + 2;
}
Edit2: To run your program I made several changes for I/O things you did that don't work in my copy of GCC. Hopefully those won't distract from the main point of the following code. I also added a second, more complicated and more accurate method of computing the answer to see how much was lost in floating point rounding.
So this code computes the answer twice, once by the method I suggested you change your code to and once by a more accurate method (using double instead of float and adding the numbers in the more accurate sequence via a recursive function). Then it display your answer and the difference between the two answers.
Running that shows the version I suggested gets all the displayed digits correct and is only wrong for the values of a I tried by tiny amounts that would need more display precision to notice:
#include<iostream>
using namespace std;
double fac_sum(int n, int a, double f)
{
if ( n > a )
return 0;
f *= n * (n-1);
return fac_sum(n+2, a, f) + 1 / f;
}
int main()
{
int a, n = 1;
float f = 1;
float s = 0;
cin >> a;
while(n < a)
{
f = f * n * (n+1);
s += 1 / f;
n = n + 2;
}
cout << s;
cout << " approx error was " << fac_sum( 2, a, 1.0)-s;
return 0;
}
For 8 that displays 0.54308 approx error was -3.23568e-08
I hope you understand the e-08 notation meaning the error is in the 8'th digit to the right of the .
Edit3: I changed f to float in this post because I had copied/tested thinking f was float, so parts of my answer didn't make sense when f was int

Multiplying integers the long way

I'm trying to create long int multiplication function. In math for multiplying 2 numbers for example 123 X 456, I do:
(12 * 10^1 + 3)( 45 * 10^1 + 6) =
(540 * 10^2) + (72 * 10^1) + (135 * 10^1) + 18 = 15129
I created a small program for this algorithm but it didn't work right.
I don't know where my problem is. Can you help me to understand and correct that?
Tnx
int digits(int n) {
int digit = 0;
while (n>0){
n/=10;
digit++;
}
return digit;
}
long int longMult(long int a, long int b) {
long int x,y,w,z;
int digitA = digits(a);
int digitB = digits(b);
if((a==0) || (b==0)) {
return 0;
} else if (digitA < 2 || digitB < 2) {
return a*b;
} else {
int powA = digitA / 2;
int powB = digitB / 2;
//for first number
x = a/(10^powA);
y = a%(10^powA);
//for second number
w = b/(10^powB);
z = b%(10^powB);
return ( longMult(x,w)*(10^(powA*powB)) + longMult(x,z) +
longMult(w,y)*(10^(powA*powB)) + longMult(y,z));
}
}
int main()
{
cout << digits(23) << endl; // for test
cout << longMult(24,24); // must be 576 but output is 96
return 0;
}
The expression
10^powA
does a bitwise exclusive or, and doesn't raise 10 to the power of powA, as you appear to expect.
You may want to define something like
long powli(int b, long e) {return e?b*powli(b,e-1):1;}
Then instead you can use
powli(10,powA)
Edit: There is also a problem with the way the values are combined:
return ( longMult(x,w)*(10^(powA*powB)) + longMult(x,z) +
longMult(w,y)*(10^(powA*powB)) + longMult(y,z));
Look into the maths, because multiplying the exponents makes little sense.
Also the combinations of adjustments to values is wrong, eg (10*a + b)(10*c + d) = 10*10*a*c + 10*a*d + 10*b*d +b*d. So check on your algebra.