編程題_飢餓的小易

題目詳述

題目鏈接:飢餓的小易

題目解析

4x + 3 = 2*(2x + 1)
8x + 7 = 3*(2x + 1)

從起點開始每次x0x_0 = 2*x0x_0 + 1,統計做了多少次2x0x_0 + 1後模1000000007等於0,再把次數分解成若干個3與2的和,3的個數加上2的個數最小,不超過100000。

程序測試

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int x0 = sc.nextInt();
        if((x0<<1)+1 == 1000000007){ // 排除x0=500000003時,一個2*x+1就可以整除1000000007,但無法移動到此處
                System.out.println("-1");
                return;   
        }
        int count = 0;
        while (x0 != 0 && count <= 300000) { //最多循環100000次,若每次走的都是8*X+7,相當於2*X+1,走300000次
            x0 = ((x0 << 1) + 1) % 1000000007; //計算(x*2+1)% 100000000
            count++;
        }
        
        int res = (count + 2) / 3; 
        //如果count%3爲0結果就是count/3,count%3爲1和2就是count/3+1,這兩種情況結果都是(count+2)/3
        //int res=(count + 2)/3等價於int res = count%3 == 0 ? count/3 : count/3 + 1
        
        System.out.println(res > 100000 ? -1 : res);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章