문방구앞오락기 2017. 7. 24. 11:17

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*Given the triangle of consecutive odd numbers:
 
             1
          3     5
       7     9    11 
   13    15    17    19 
21    23    25    27    29
31 33 35 37 39            41
43  45  47  49  51   53     55  
...
Calculate the row sums of this triangle from the row index (starting at index 1) e.g.:
 
rowSumOddNumbers(1); // 1
rowSumOddNumbers(2); // 3 + 5 = 8
*/
public class CodeWar_4 {
 
     public static int rowSumOddNumbers(int n) {
 
         int end =1;
         int t=2;
         int count=0;
         int sum=0;
         
         if(n==end){
             
             return n;
         }
         
        for(int i = 1 ; i<=n-1; i++){
            count=t*2;
            t++;
            end =end+count;
        }
         
        System.out.println(end);
         
        for(int i=n ; i> 0; i--){
            System.out.println(end);
            sum=sum+end;
            end =end-2;
        }
        
        System.out.println(sum);
        
         
         return sum;
            
      }
    
     public static int best_rowSumOddNumbers(int n) {
            /* sum of consequent M numbers is (M+1)M/2, so 
             * we may know how many numbers were below
             * our ROW : numbersBelow = ((n-1)*(n))/2.
             * Now we may calculate first number in row:
             * firstNumberInRow = 2*numbersBelow+1.
             * So, firstNumberInRow = n*n-n+1 and
             * last number in ROW is n*n-n+1 + 2(n-1).
             * Let assume that last number before row is
             * x1 and last number in row is x2. It's known
             * that 1+3+5+...+(2k-1) = k*k.
             * Sum in row must be x2*x2 - x1*x1. 
             // OUR x1 = (n*n-n)/2 and x2 = (n*n+n)/2.
             * After some simplification: SUM = n*n*n. */
          return n*n*n;
          }
     
    
    
    public static void main(String[] args) {
        
        CodeWar_4 c = new CodeWar_4();
            c.rowSumOddNumbers(42);
    
        
    }
}