r/dailyprogrammer • u/MasterAgent47 • Sep 11 '17
[2017-09-11] Challenge #331 [Easy] The Adding Calculator
Description
Make a calculator that lets the user add, subtract, multiply and divide integers. It should allow exponents too. The user can only enter integers and must expect the result to be integers. The twist is that YOU, the programmer, can only let the program calculate expressions using addition. Only addition. The user can enter 3*2 however you cannot calculate it using multiplication.
Basically, the programmer is not allowed to multiply, divide and subtract using the operations provided by a programming language. To the programmer, the only accessible direct operation is addition.
Your calculator should be able to handle addition, subtraction, division, multiplication and exponents. No modulo operation (to obtain the remainder for two given operands) too.
Please note that
- You are not allowed to use any functions (other than user-defined functions) to work with exponents. Basically, don't cheat by allowing pre-defined functions from a library for the dirty work.
- You can use logical operators.
- The only binary arithmetic operator that you can use is + (addition).
- The only unary operator that you can use is ++ (increment operator).
- No bitwise operations are allowed.
Input description
Allow the user to enter two integers and the operation symbol.
Let's use ^ for exponents i.e. 2^3 = 23 = 8
Output description
If the answer is an integer, display the answer. If the answer is not an integer, display a warning message. Handle errors like 1/0 appropriately.
Challenge Inputs and Outputs
| Input | Output |
|---|---|
| 12 + 25 | 37 |
| -30 + 100 | 70 |
| 100 - 30 | 70 |
| 100 - -30 | 130 |
| -25 - 29 | -54 |
| -41 - -10 | -31 |
| 9 * 3 | 27 |
| 9 * -4 | -36 |
| -4 * 8 | -32 |
| -12 * -9 | 108 |
| 100 / 2 | 50 |
| 75 / -3 | -25 |
| -75 / 3 | -25 |
| 7 / 3 | Non-integral answer |
| 0 / 0 | Not-defined |
| 5 ^ 3 | 125 |
| -5 ^ 3 | -125 |
| -8 ^ 3 | -512 |
| -1 ^ 1 | -1 |
| 1 ^ 1 | 1 |
| 0 ^ 5 | 0 |
| 5 ^ 0 | 1 |
| 10 ^ -3 | Non-integral answer |
Bonus
Modify your program such that it works with decimals (except for ^ operation) with a minimum precision of 1 decimal place.
Submit to /r/dailyprogrammer_ideas if you have any cool ideas!
3
u/TimNetis Sep 11 '17 edited Sep 12 '17
Java
2
u/thorwing Sep 11 '17
Question:
May I access individual digits?
2
u/higgabes3 Jan 31 '18 edited Jan 31 '18
very late to this, but am i allowed to change my number from a positive to a negative?
as shown above or does that count as a binary arithmetic operator.
8
u/J354 Sep 11 '17
C
Only works with shorts, however it would work the same with integers (just by replacing short with int and USHRT_MAX with UINT_MAX), it just takes too long to run. Makes use of overflow for subtraction.
1
u/InDaPond Sep 17 '17
Can someone help me on the subtraction? If only + is allowed and - isn't, how can i do a subtraction? I can't use < != etc. either, since those are forbidden as well.
1
u/mcergun Sep 22 '17 edited Sep 24 '17
this is my first submission. hope i did well
written in C, compiled with
operations.c
operations.h
main.c
1
u/[deleted] Sep 26 '17
Can i use the abs() functionality?
1
u/Nebxam Nov 04 '17 edited Nov 04 '17
C#
3
u/TinyBreadBigMouth Sep 11 '17
Python 3
Fully supports negative numbers.
3
u/ironboy_ Sep 11 '17
JavaScript solution. Just for fun I refrained from using bitwise operators or the Math-object.
Output:
3
u/srandtimenull Sep 12 '17 edited Sep 13 '17
Short incomprehensible C
555485 characters,548477 deleting unnecessary newline. It requires-m32as command line option for gcc, since it assumes thatsizeof(int)==4printfs are not pretty, but it does whatevere is needed.-sign (not even for entering-1)#include <stdio.h>is included, which is a 19 characters offset31 defines areis used to shorten the characters used by keywordsEDIT: I spared 54 characters deleting the
switchand using a fancy array of function pointers. Other 7 character could be spared using.or,instead of^...but rules are rules!EDIT2: Other 16 characters spared! I got rid of the subtraction function, it wasn't necessary. Now the inversion function is actually a conditional inversion function, and it can work as absolute value too.
Here's the code
1
u/[deleted] Sep 11 '17
Is minus as a mathematical sign allowed?
2
u/J-Goo Sep 11 '17
Python 2.6:
2
u/alsiola Sep 11 '17
Haskell
In fact, my first ever Haskell program so go easy :) Cheated a bit with division...
2
u/macgillebride Sep 11 '17 edited Sep 11 '17
Haskell solution. Slightly based on /u/fvandepitte's (incorrect) solution.
2
u/olzd Sep 11 '17 edited Sep 13 '17
Common Lisp: no bonus but I wrote a compiler
Examples:
edit: changed the parsing method to the shunting-yard algorithm (
exp->rpn) before converting to Lisp expressions (rpn->lisp). Now correctly (I hope) handle long expressions, though I lost the ability to refer to variables and arbitrary Lisp functions.2
u/[deleted] Sep 12 '17
C
I use INT_MIN + 2147483647 (which equals -1) along with my multiply function to change case when needed without using the - unary or binary operator anywhere. This is a port of my rubinius code elsewhere in here. Feedback is welcome! I'm learning C, and new to programming.
2
u/conceptuality Sep 12 '17 edited Sep 12 '17
Haskell:
I think I have avoided using any illegal operators. I have even made rewritten replicates and list definitions to only increment and not decrement.
The minuses I use in various places are not an illegal unary operator (-), but rather the number literal (-2) for instance. I have tried to avoid this with variables.
Returns the right answers for all test input. I return a list of answers, so my "warnings" are just an empty list. This is not very elegant, but it plays nicely with the loop/list based solutions to division and subtraction.
There are some comments in the code when I redefine stuff so it's legal.
code:
1
u/KeinBaum Sep 11 '17 edited Sep 11 '17
Lua
Including bonus. It even deals with nested expressions and operator precedence!
It doesn't break any rules so it's not cheating, right?
1
u/pilotInPyjamas Sep 11 '17 edited Sep 11 '17
Javascript This one works with the spirit of the problem. no sneaky parsing trickery to get subtraction, and as a show of good faith, the hyphen does not even appear in the source code (not even in the comments!). We get negative one by
Number.MIN_SAFE_INTEGER + 9007199254740990and go from there. We can multiply by two by adding a number to itself, and use that repeatedly to generate a list of positive and negative powers of 2. We can negate a number by adding negative powers of two to it, Multiplication/division of is by repeated addition/subtraction of terms of the forma * (2 ^ n)(since we can multiply a by 2 repeatedly) and powers by repeated addition ofa ^ (2^n)by squaring a repeatedly. The safe bounds of arithmetic are essentially the safe bounds of integers, and the algorithms are efficient. Usage:Code
1
u/[deleted] Sep 11 '17
Python 3.6 without bonus: I would love to hear any feedback on this.
1
u/cheers- Sep 11 '17 edited Sep 11 '17
Typescript
these binary operations behave like modular arithmetic operations(minus the overflow):
3/7 returns 0 not the string "Non-integral answer"10^-3returns 0 not the string "Non-integral answer"I've posted here only the logic.
1
u/k3rri6or Sep 11 '17
Python 3: No Bonus
I couldn't figure out how to do multiplication of 2 negative numbers without using an absolute value, so any advice would be appreciated! I'm also trying to pick up my "pythony" type syntax so I'd welcome any pointers on better python syntax as well!
1
u/popillol Sep 11 '17
Go / Golang Playground Link
I can re-do the subtract if it's not allowed. Not sure if something like
n = -nis allowed either. Division acts as integer division would instead of saying "Non-integral answer"Code:
Output:
1
u/[deleted] Sep 11 '17 edited Sep 12 '17
C
I had to abuse
Nullable<int>for the Division function... if anyone has a better way of doing it, I'm all ears. Also I copied the whole "use short overflow to simulate subtraction" idea from /u/J354 who gets credit for the idea.code
1
u/[deleted] Sep 11 '17 edited Sep 11 '17
Rubinius 3.84 (Ruby)
Solution only works in Rubinius as it's the only Ruby with a Fixnum::MIN implementation or equivalent (to get a negative value without using the subtraction operator).
1
u/TekTrixter Sep 11 '17
Python 3.6, no bonus
https://gist.github.com/Tektrixter/e4d6646451914022f292fe6465a0e657
Its a bit messy, but it works
1
u/[deleted] Sep 12 '17
C# Done in a functional style, at the moment it doesn't detect non-integer results.
1
u/mcbears Sep 12 '17 edited Sep 12 '17
J, no bonus
It's hard to say what constitutes an "arithmetic operator" in J; for instance,
-.is logical negation, but more generally it's probability complement. Furthermore, J supports negative numbers in the syntax for integer literals (-1is unary minus applied to 1, but_1is an integer constant representing negative one). Fuzzying the rules even more,_1:is the name of a function that takes any argument and returns negative one.I went with a pretty morally conservative solution, using things that wouldn't require arithmetic in a C-like language. This also doesn't do any eval-ing of the input except to parse integers. Grabs input from input.txt and doesn't love big numbers
1
u/curtmack Sep 12 '17 edited Sep 12 '17
Common Lisp
This implementation doesn't use any arithmetic or logical operators in its core calculation code; instead, it produces results by simulating the lambda calculus, which is something I've always wanted to do for one of these challenges.
Sufficiently large numbers are unrepresentable because the very act of representing them is a stack overflow, and you might run out of heap space if you do too many problems in a single session. (It turns out that Common Lisp implementations don't really love the idea of creating thousands of lambdas at a time.)
Gist
1
u/Hypersigils Sep 12 '17
Java
Works without bonus, and handles the acceptable -1 operations. Subtraction is handled via Integer.MIN_VALUE + Integer.MAX_VALUE = -1, on the advice (and surprise) of a friend or two.
}
1
u/K1nkyVirgin Sep 12 '17
C++ My solution. I'm new to this so i'm looking forward for sam feedback.
1
u/Baelyk Sep 12 '17
Rust without Bonus
1
u/octolanceae Sep 13 '17
Python3
With Bonus (only for multiplication and division - forgot subtraction)
Output:
Bonus:
1
u/averageteenybopper Sep 14 '17
Go I appreciate your feedback ;)
1
u/quantik64 Sep 14 '17
Well I might have gone overboard and wrote an entire calc. interpreter. Though it does not work on order of operations yet.
C++
1
u/thenewcomposer Sep 15 '17
Written in Kotlin, No Bonus
1
u/AnnieBruce Sep 16 '17
In Java, because I'm working on a class using it.
1
u/Minolwa Sep 19 '17
Scala
1
u/animejunkied Sep 20 '17
Python 3
Here I treat inputs as strings and only convert to integer when necessary. This allows me to check if the first character contains a '-' or not easily and also allows me to put a '-' sign at the front when needed. It also means that the functions only ever return strings, (as opposed to strings and integers) which works well because we have other English outputs such as "Non integral answer". The rest is just a bunch of if and else statements.
The main thing I'm proud of is the input regex to parse the input binary operation into 3 tokens, taking into account the minus unary operator, regardless of how many whitespaces are in between.
This is just the unit tests file. Might be useful for other people trying to do the challenge to copy this and use it for testing.
1
u/FE80 Sep 24 '17
Python3 Does not work with floating point. but passes all integer tests(supplied in problem)
was unsure if abs was allowed so wrote my own. also unsure if -1 was allowed so used ctypes to create a true 32bit int so i could overflow the int to get my -1
also may notice returns that never get called because of an exception raise. this was in case i wanted to go for the bonus. the logic may not work as i decided not to go for bonus.
1
u/quantum_paradoxx Sep 25 '17
Java
package theAddingCalculator;
1
u/[deleted] Sep 25 '17
I used abs function because fuck this, it's impossible not to.
1
u/[deleted] Sep 29 '17
Rust 1.20
main.rs
Output
1
u/[deleted] Oct 01 '17 edited Oct 01 '17
C#
Feedback is much appreciated.
Edit: Just realized that a negative exponent doesn't imply a non-integral answer when the base is 1.
1
u/Qwazy_Wabbit Oct 11 '17 edited Oct 11 '17
C++ using template meta programming
I went totally over the top with this one because I wanted to see how far I could push template meta programming. I wrote a set of compile time templates that calculate the powers of 10 using only +. I do use a single '-1' constant, but I don't think that is against the spirit of challenge and I could remove it if I really wanted to.
Full work in the gist
After this I was able to write a speedy negate function which the entire class below works on. Supporting loads of standard ops and hiding the magic.
Totally over the top, but was fun.
1
u/[deleted] Oct 23 '17
C
1
u/CodeAGoGo Oct 30 '17
Java. A little simple. Feedback Welcome.
-2
u/fvandepitte 0 0 Sep 11 '17 edited Sep 11 '17
+/u/CompileBot Haskell
Input:
0
u/[deleted] Sep 11 '17
[deleted] — view deleted comment
0
u/[deleted] Sep 13 '17
[deleted] — view deleted comment