天天看點

牛客網程式設計題:進制均值

牛客網程式設計題:進制均值

題目描述

盡管是一個CS專業的學生,小B的數學基礎很好并對數值計算有着特别的興趣,喜歡用計算機程式來解決數學問題,現在,她正在玩一個數值變換的遊戲。她發現計算機中經常用不同的進制表示一個數,如十進制數123表達為16進制時隻包含兩位數7、11(B),用八進制表示為三位數1、7、3,按不同進制表達時,各個位數的和也不同,如上述例子中十六進制和八進制中各位數的和分别是18和11,。 小B感興趣的是,一個數A如果按2到A-1進制表達時,各個位數之和的均值是多少?她希望你能幫她解決這個問題? 所有的計算均基于十進制進行,結果也用十進制表示為不可約簡的分數形式。

輸入描述:

輸入中有多組測試資料,每組測試資料為一個整數A(1 ≤ A ≤ 5000).

輸出描述:

對每組測試資料,在單獨的行中以X/Y的形式輸出結果。

示例1

輸入

5

3

輸出

7/3

2/1

import java.util.Scanner;

public class Main

    static int count(int n, int i) {
        int sum = 0;
        while(n > 0) {
            sum += n % i;
            n /= i;
        }
        return sum;
    }

    static int solution(int n) {
        int sum = 0;
        for(int i = 2; i <= n-1; i++) {
            sum += count(n,i);
        }
        return sum;
    }

    static int gcd(int a, int b) {
        while(b != 0) {
            int temp = a % b;
            a = b;
            b = temp;
        }
        return a;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()) {
            int n = sc.nextInt();
            int y = n - 2;
            int x = solution(n);

            int g = gcd(y,x);
            y /= g;
            x /= g;            
            StringBuilder sb = new StringBuilder();
            sb.append(x).append("/").append(y);
            System.out.println(sb.toString());
        }
        sc.close();
    }
}