0
Java
write a program to find sum of all natural numbers from one to hundered in java
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.
+ 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).
0
if anybody know the answer
0
write a program to find sum of all natural numbers from one to hundered
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 :)
0
wrong answer
0
I assure you 5050 is the right answer :)
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);
}
}