+ 1

Stuck in java

In the following code, which i designed to calculate the sum of whole numbers. Whenever I enter a number greater than or equal to 10000000, the answer comes in negative https://code.sololearn.com/clR4yAfuXQer/?ref=app

23rd Dec 2019, 6:30 AM
Devashish Mishra
Devashish Mishra - avatar
3 Answers
+ 3
use long instead of int to deal with larger values
23rd Dec 2019, 6:46 AM
George Samanlian
+ 2
long sum is enough + you can check overflow this way: int sum=0, x=0; // int for this test, long is better try { for (x = 0 ; x <=new1 ; ++x){ // sum = sum + x ; sum = Math.addExact(sum, x); } } catch (ArithmeticException e) { System.out.println("Numeric overflow" +" x = " +x); } System.out.println("sum = "+sum);
23rd Dec 2019, 10:18 AM
zemiak
+ 1
int data type has a limit(2^31-1) All data types have a limit So for huge numbers use long or double data type
24th Dec 2019, 3:49 PM
Marvellous Person
Marvellous Person - avatar