0

Java

write a program to find sum of all natural numbers from one to hundered in java

31st Jul 2019, 6:58 PM
Chadalavaa Sai
8 Answers
+ 2
public class Program { public static void main(String[] args) { int sum = 0; for(int i=1, j=100; i<=50; i++, j--) { sum += (i+j); } System.out.println(sum); } } A little homage to immortal genius of Gauss.... once it was a child, Gauss' teacher gave the class task to sum numbers from 1 to 100, to take them busy for an hour or so. After a few seconds, Gauss answered "5050"! He reasoned so: sum 1 and 100, you get 101. Sum 2 and 99, you get 101. Sum 3 and 98, you get 101. And so on, for all 50 couples you can form. So, result is 101 * 50 = 5050.
31st Jul 2019, 7:04 PM
Paolo De Nictolis
Paolo De Nictolis - avatar
+ 2
it's an arithmetic progression, then: sum = ((1+100)/2)*100; (S = ((a1+a2)/2)*n) why is it better? Cause complexety of codes before this is O(n), this code is O(1).
31st Jul 2019, 9:56 PM
Marina Vasilyova
Marina Vasilyova - avatar
0
if anybody know the answer
31st Jul 2019, 6:58 PM
Chadalavaa Sai
0
write a program to find sum of all natural numbers from one to hundered
31st Jul 2019, 6:59 PM
Chadalavaa Sai
0
Now please improve my code taking a number from user as input, and outputting the sum of all numbers from 1 to that number :)
31st Jul 2019, 7:06 PM
Paolo De Nictolis
Paolo De Nictolis - avatar
0
wrong answer
31st Jul 2019, 7:19 PM
Chadalavaa Sai
0
I assure you 5050 is the right answer :)
31st Jul 2019, 7:20 PM
Paolo De Nictolis
Paolo De Nictolis - avatar
0
But perhaps you wanted this: public class Program { public static void main(String[] args) { int sum = 0; for(int i=1; i<=100; i++) { sum += i; } System.out.println(sum); } }
31st Jul 2019, 7:22 PM
Paolo De Nictolis
Paolo De Nictolis - avatar