Monday, August 18, 2014

Hackerrank Ad Infinitum August 2014 - Stepping Stones Game solution

Hackerrank Ad Infinitum August 2014 - Stepping Stones Game: https://www.hackerrank.com/contests/infinitum-aug14/challenges/stepping-stones-game

Hackerrank Ad Infinitum August 2014 - Stepping Stones Game editorial: https://www.hackerrank.com/contests/infinitum-aug14/challenges/stepping-stones-game/editorial

Hackerrank Ad Infinitum August 2014 - Stepping Stones Game solution: 


#include <iostream>
#include <cstdio>
#include <cmath>

int main() {
    int t;
    long long int n, a;
    scanf("%d", &t);
    while(t--) {
        scanf("%lld", &n);
        if(floor(sqrt(1+8*n))==sqrt(1+8*n)) a=(sqrt(1+8*n)-1)/2, printf("Go On Bob %lld\n", a);
        else printf("Better Luck Next Time\n");
    }
    return 0;
}

note: The formular for the sum of the first 
n natural numbers is
n(n+1)2
A number x appears in this sequence, iff
n(n+1)2=xn2+n2x=0
has an non-negative integer solution. Since, this is a quadratic equation, you can simply compute the positive solution:
n=1+8x12
This is an integer number, iff 1+8x is a square and 21+8x1. You can see, that the latter is always true, if the former is true. So the answer is:
x occurs in this sequence, if 1+8x is a perfect square.

ref: http://math.stackexchange.com/questions/466649/how-do-i-test-if-a-number-x-is-a-sum-of-consecutive-natural-numbers

No comments:

Post a Comment