• + 0 comments

    ini solusi tanpa looping, dengan merumuskan masalah menjadi sebuah pola

        public static long strangeCounter(long t)
        {
            // 1, 4, 10, 22, 46 .... Un
            // 1 + (3* (2^0 - 1) => 1
            // 1 + (3* (2^1 - 1) => 4
            // 1 + (3* (2^2 - 1) => 10
            // 1 + (3* (2^3 - 1) => 22
            // 1 + (3* (2^4 - 1) => 46
            // 1 + (3* (2^5 - 1) => 94
            // ...
            // 1 + (3* (2^n - 1) => formula for the n-th term
    
            // how to get n from (2^n - 1), log2 (floor(time+2)/2)
            long n = (int)Math.Floor(Math.Log((t+2) / 3, 2));
            
            long topValue = long.Parse((3 * Math.Pow(2, n)).ToString());
            long topTime = topValue - 2;
    
            return topValue - (t - topTime);
        }