## DEV Community is a community of 757,079 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

dev.to staff

Posted on

# Daily Challenge #143 - Big Arithmetic

Doing arithmetic with big numbers is impossible to do with regular integer types. In JavaScript (which represents numbers as 64-bit floats), anything beyond 2^53-1 becomes increasingly less accurate.

Write a two functions (`bigAdd` and `bigSub`) to accurately represent these large integers as strings. They will both take two arguments: either a valid representation of an integer as a string, or a regular number. They will return the correct answer as a string. `bigAdd` will sum, `bigSub` will subtract.

For example:
`bigAdd(1, "123456789012345678901234567890") === "123456789012345678901234567891";`
`bigSub("123456789012345678901234567890", 1) === "123456789012345678901234567889";`

Remember, the values could be negative, and so the calculations should be made accordingly.
`bigAdd(-1, "123456789012345678901234567890") === "123456789012345678901234567889";`
`bigSub("123456789012345678901234567890", -1) === "123456789012345678901234567891";`

Tests

```
bigSub("123456789012345678901234567890", 1)
bigSub("123456789012345678901234567890", -1)
```

This challenge comes from wthit56 on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!

Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!

## Discussion (4)

Yechiel Kalmenson

Thankfully, Ruby automatically converts ints to Bignums when it detects an overflow, so the Ruby solution is as simple as:

``````def big_add(a, b)
(a.to_i + b.to_i).to_s
end

def big_sub(a, b)
(a.to_i - b.to_i).to_s
end
``````
Craig McIlwrath

``````bigAdd :: Integer -> Integer -> Integer

bigSub :: Integer -> Integer -> Integer
bigSub = (-)
``````

It isn't feaaible/doesn't make sense to define similar methods that take various combinations of strings and integers. Especially in a language with support for literals of arbitrarily sized integers.

In JavaScript.

``````const bigAdd = (a, b) => (BigInt(a) + BigInt(b)).toString();
const bigSub = (a, b) => (BigInt(a) - BigInt(b)).toString();
``````
Chandra Shekhar

Java :)

import java.math.BigInteger;

public class BigArithmetic {

``````public static void main(String[] args) {
System.out.println(bigSub("123456789012345678901234567890", 1));
System.out.println(bigSub("123456789012345678901234567890", -1));
}

private static String bigSub(Object a, Object b) {