4
\$\begingroup\$

The code below prints sum from 1 to 10:

\$1\$
\$1+2 =\$
\$1+2+3 =\$
\$1+2+3+4 =\$
\$......\$
\$1 + ... 10 = 55\$

public class Solution{

    public static void print_sums(){

        int sum = 0 ;
         for(int i = 1 ; i <= 10 ; i++){
             for(int j = 1 ; j <= i; j++ ){
                sum = sum + j ;
             }
             System.out.println( sum) ;
             sum = 0 ;
         }

    }

    public static void main(String[] args)
    {
        print_sums() ;


    }
}

I wonder out of "efficiency curiosity" - is it possible to do it in 1 loop? Without 2 nested loops?

i.e. put both i and j in one loop and increment them from there.

I think it is impossible, because **the whole loop will run only 10 times - i = [1,10]

 for(int i = 1 , j = 1 ; j <= i && i <= 10 ; i++, j++)
             //for(int j = 1 ; j <= i; j++ ){
                sum = sum + j ;
             //}
             System.out.println( sum) ;
             sum = 0 ;
\$\endgroup\$
  • 1
    \$\begingroup\$ Clearly it is possible to do without any loops. \$\endgroup\$ – emory Aug 2 '14 at 21:42
  • \$\begingroup\$ @emory : yes but only to calculate it once, not to print it in each step \$\endgroup\$ – bhathiya-perera Aug 6 '14 at 10:10
  • 1
    \$\begingroup\$ It is a one liner ... println(1\n3\n6\n...) using a loop would be easier but it is not necessary. \$\endgroup\$ – emory Aug 6 '14 at 12:08
  • \$\begingroup\$ if you do it recursively it should be fairly simple \$\endgroup\$ – user80793 Aug 9 '15 at 5:00
  • 1
    \$\begingroup\$ @emory imagine the problem is 1 to N. \$\endgroup\$ – ANeves Aug 9 '15 at 13:11
14
\$\begingroup\$

Yes, it is possible.

public static void printSums() {
    int sum = 0;
    for (int i = 1; i <= 10; i++) {
        sum += i;
        System.out.println(sum);
    }
}

The key is simply to calculate the sum of the first \$N\$ digits. It is easy if you already have the sum of the first \$N-1\$ digits : you simply add \$N\$.

\$\endgroup\$
  • 2
    \$\begingroup\$ And this is a good example of a primitive form of memoization \$\endgroup\$ – rolfl Aug 2 '14 at 14:52
  • 2
    \$\begingroup\$ Be careful with your loop limits! And look carefully before accepting an answer! \$\endgroup\$ – 200_success Aug 2 '14 at 15:12
  • 1
    \$\begingroup\$ @200_success, yes , it should be i <=10 : less than or equal \$\endgroup\$ – ERJAN Aug 2 '14 at 15:18
14
\$\begingroup\$

Another solution without the mutating sum temporary variable is using the \$n * (n + 1) / 2\$ formula:

public static void printSums() {
    for (int i = 1; i <= 10; i++) {
        System.out.println(i * (i + 1) / 2);
    }
}
\$\endgroup\$
  • 3
    \$\begingroup\$ In general using the gaussian sum is better than actually calculating the sum. In this case, I suspect the accepted answer would be more efficient. \$\endgroup\$ – emory Aug 2 '14 at 21:44

Not the answer you're looking for? Browse other questions tagged or ask your own question.