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
Related
I'm trying to find a solution to a task. My code passed only 3 autotests. I checked that the solution satisfies the max/min cases. Probably there are situations when my code is not valid.
Description of the task: Find the remainder after dividing the sum of two integers by the third.
Input: The first line of input contains two integers A and B (-10^18 ≤ A, B ≤ 10^18). The second line contains an integer C (2 ≤ C 10^9).
Output: Print the remainder of dividing A + B by C.
My code:
#include <iostream>
// int64_t
#include <cstdint>
#include <stdint.h>
// #include <math.h>
// 3 tests passed
int main() {
int64_t a, b, c;
std::cin >> a >> b >> c;
// a = pow(-10, 18);
// b = pow(-10, 18);
// // c = pow(10, 9);
// c = 3;
// c = pow(10, 18) - 20;
// c = 1000000000000000000 + 1;
// c = 1000000000000000000 + 2;
// std::cout << a << std::endl;
// std::cout << b << std::endl;
// std::cout << c << std::endl;
std::cout << (a + b) % c << std::endl;
return 0;
}
Please note that in C++ reminder for negative values:
was implementation defined until C++11
integer division is rounded towards zero since C++11 which makes reminder negative sometimes.
Now most probably in your task modulo result should be always in range <0, C) (or written differently <0, C - 1>). So to handle cases where A + B is negative, you have to take this into account that reminder may be negative.
So your code can look like this:
nt main() {
int64_t a, b, c;
std::cin >> a >> b >> c;
std::cout << (a + b) % c + ((a + b) % c < 0) * c << '\n';
return 0;
}
Which basically adds c to result if result is negative and makes result inside required range. (assuming c is positive).
Modulo operation in C++ uses truncated division, i.e., the result of x % y is negative if x is negative.
To obtain a non-negative result congruent to (a + b) % c, you can use ((a + b) % c + c) % c.
I believe the point of the exercise is to handle overflows and underflow by realizing that the remainder of the sum is the sum of the remainder modulo c.
That's what my magic-8 ball says anyway. If that's not the solution the provide the failed input and expected and actual output.
So essentially, I'm trying to code a small block that should create or generate coefficients for polynomial n-degree that can be represented through vector which is a=[a0, a1..an] given the basic formula is
Well, the issue is when doing a function to get value of polynomial P from point "x" it returns value from entirely using Horner's Rule which it's not the same result as intended although not sure which one I should put on. The math basic explanation tells me at least something out of:
E.g: n=2; (A[i] stack terms by 4, 2, 1) and calculates P(value of x) = 4 * x ^ 0 – 2 * x ^ 1 + 1 * x ^ 2 = 4 – 2x + x2 = x2 – 2x + 4 = 4
With other words , can't find the culprit when for "x" value is meant to go through "i" variable numbered wrong by exponent and the result gets output for P(0)=7 while it shouldn't be and concrete as in P(0) = 0 ^ 2 – 2 * 0 + 4 = 4
Here's a little snippet went through so far, I would appreciate if someone could point me in the right direction.
double horner(const double&x, const int& n, const double& nn) {
if (n < 0)
return nn;
else {
double m; cin>>m;
return horner(x, n-1, nn*x+m);
}
}
int main() {
int n;double x;
cout << "n=";cin >> n;
cout << "x=";cin >> x;
cout << "P(0)=" << horner(x, n, 0);
return 0;
}
Edit: My brain farted for a moment somewhere while was coding and continuously revising the case, I forgot to mention what exactly are the parts of each variables for the program to avoid confusion yes, so:
n, polynomial grade;
p, polynomial coefficient;
x, the point in which evaluates;
And here given the grade equation to polynomial
which any negative and positive input terms adding by exponent to these coefficients are the steps that holds the result exception, hence the reason Horner's rule that it reduces the number of multiplication operations.
Edit: After few hours, managed to fix with polynomial evaluating issue, the only question remains how I'd suppose to generate coefficients using method std::vector ?
float honer(float p[], int n, float x)
{
int i;
float val;
val = p[n];
for (i = n - 1; i >= 0; i--)
val = val * x + p[i];
return val;
}
int main()
{
float p[20]; // Coefficient of the initial polynomial
int n; // Polynomial degree -n
float x; // Value that evaluates P -> X
cout << "(n) = ";
cin >> n;
for (int i = n; i >= 0; i--)
{
cout << "A[" << i << "]=";
cin >> p[i];
}
cout << "x:= ";
cin >> x;
cout << "P(" << x << ")=" << honer(p, n, x);
//Result (input):
//n: 2,
//P[i]: 4, -2, 1 -> x: 0, 1
// Result (output):
//P() = 4
}
Expect some certain output scenarios given below input if assigned:
#include <cmath> \\not sure if I need cmath
#include <iostream>
using namespace std;
this while loop serves to loop the " enter number of terms to approximate.
while (a != 0)
{
here is the Leibniz formula:
double c = 0.00, d = 0.00;
for (int i = 1; i <= a)
{
if (i % 2 != 0)
{
d = 1 / (1 + 2 * (i - 1));
}
else
{
d = -1 / (1 + 2 * (i - 1));
}
c = c + d;
i = i + 1
}
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(5);
cout << "The approximation for Leibniz's Formula is " << c << "
using "<< a <<" terms." << endl;
here is the Wallis formula:
double e = 1.00;
for (int u = 0; u<a; u++)
{
e = e * (2 * a / (2 * a - 1))*(2 * a / (2 * a + 1));
}
cout << "The approximation for Wallis' Formula is " << e << " using
"<< a <<" terms." << endl;
cout << endl;
cout << "Enter the number of terms to approximate (or zero to
quit):" << endl;
cin >> a;
}
For a=1 I am getting 1.0000 in the first formula output and 0.00000 in the second formula output
A line like this
d = 1 / (1 + 2 * (i - 1));
will use integer arithmetics to calculate the result, and then convert the int result to a double.
Change it to
d = 1.0 / (1 + 2 * (i - 1));
or even
d = 1.0 / (1.0 + 2.0 * (i - 1.0));
There are many mistakes in this code. First, comments in c++ use //, not \\.
#include <cmath> //not sure if I need cmath
You have to have two semicolons in for statements, even if you don't need loop-expression.
for (int i = 1; i <= a;)
The d will evaluate to 0 for every i that is greater than 1. You are using integer division, when you clearly want floating point division. You have to tell that to the compiler like this.
d = 1.0 / (1 + 2 * (i - 1));
When the left argument of division operator is double compiler will know, that you want to perform a floating point division. If it would be int as in your code, integer division would be performed and result converted to double.
Also in the Wallis formula you misplaced a for u, and also u parameter should start at 1, not 0. Also the integer division problem persists here.
double e = 1.00;
for (int u = 1; u<a; u++)
{
e = e * (2.0 * u / (2.0 * u - 1))*(2.0 * u / (2.0 * u + 1));
}
If you fix this all, the program starts to output valid results.
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;
I'm having a bit of trouble figuring out recursion for this specific program. I have tried a few different options, but I am brand new to recursive functions. The only part of the program I am allowed to modify is inside of the function B.
This function calculates: Bn(a) = Bn−1(a) × Bn−2(a), where B1(a) = B2(a) = a.
So B1(a) = a | B2(a) = a | B3(a) = a^2 | B4(a) = a^3 | B5(a) = a^5 | etc...
#include <iostream>
using namespace std;
float B(float a, int n)
{
//Here is where I'm having an issue...
}
int main(void)
{ cout << "Input a float a, and an int n > 0: ";
float a; int n;
cin >> a >> n;
cout << "B(" << a << ")_" << n << " = " << B(a,n) << endl;
return 0;
}
First take care of the cases where n is 1 or 2, which are defined to return a without recursing. These are the so-called termination cases.
float B(float a, int n)
{
if (n == 1 || n == 2) { return a; }
// ...
}
Then you recurse for the others, subtracting from n each time:
float B(float a, int n)
{
if (n == 1 || n == 2) { return a; }
return B(a, n - 1) * B(a, n - 2);
}
If you pass in an n greater than 2, the recursive calls will eventually reach a termination case and execution will stop at that point, returning the final result all the way back up to the first call.
Let's take an example invocation, B(2, 4). This doesn't match the termination case, so the function will recurse, like so:
B(2, 4) will return B(2, 3) * B(2, 2).
B(2, 3) will return B(2, 1) * B(2, 2). We replace this in the original, and we get: (B(2, 1) * B(2, 2)) * B(2, 2).
All we have left now is termination cases, so we can substitute those by the value of a: (2 * 2) * 2 = 23 = 8.
As far as what actually happens (not just algebraic simplification), this will be the call tree:
B(2, 4) is not a termination case, it will call:
B(2, 3) is not a termination case, it will call:
B(2, 2) is a termination case, returning 2.
B(2, 1) is a termination case, returning 2.
The return will be 2*2 = 4.
B(2, 2) is a termination case, returning 2.
The return will be 4*2 = 8.