Monday, January 19, 2015

Topcoder SRM 639 div 2 500 problem.

If I solve this problem I sholud know find N

ex) 1+2+3+5... +N = 5050
n*(n+1)/2 = 5050




 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
package srm639;

/**
 * n(n+1)/2 = x   1+2+3+4+5+N
 * @author ddavid
 *
 */
public class AliceGameEasy {
 public static void main(String args[]){
  AliceGameEasy age= new AliceGameEasy();
  System.out.println(age.findMinimumValue(10, 0));
  System.out.println(age.findMinimumValue(932599670050l, 67400241741l));
 }
 
 public long findMinimumValue(long x, long y){
  long sqrt = (long)Math.sqrt((x+y) *2);
  if(sqrt *(sqrt +1) != (x+y) *2){
   return -1l;
  }
  long sum =0l;
  int cnt =0;
  while(sum < x){
   sum += sqrt;
   sqrt--;
   cnt++;
  }
  return cnt;
 }
}

No comments:

Post a Comment