24h購物| | PChome| 登入
2012-07-09 20:32:02| 人氣908| 回應0 | 上一篇 | 下一篇

[UVA][Java] 10669 - Three powers

推薦 0 收藏 0 轉貼0 訂閱站台

Problem B: Three powers

Consider the set of all non-negative integer powers of 3.

S = { 1, 3, 9, 27, 81, ... }

Consider the sequence of all subsets of S ordered by the value of the sum of their elements. The question is simple: find the set at the n-th position in the sequence and print it in increasing order of its elements.

Each line of input contains a number n, which is a positive integer with no more than 19 digits. The last line of input contains 0 and it should not be processed.

For each line of input, output a single line displaying the n-th set as described above, in the format used in the sample output.

Sample input

1
7
14
783
1125900981634049
0

Output for sample input

{ }
{ 3, 9 }
{ 1, 9, 27 }
{ 3, 9, 27, 6561, 19683 }
{ 59049, 3486784401, 205891132094649, 717897987691852588770249 }


轉二進制之後輸出 3^i

import java.math.BigInteger;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        BigInteger[] pow = new BigInteger[100];
        pow[0] = new BigInteger("1");
        for(int i = 1; i < 100; i++)
            pow[i] = pow[i-1].multiply(BigInteger.valueOf(3));
        while(cin.hasNextLong()) {
            long n = cin.nextLong();
            if(n == 0)
                break;
            n--;
            System.out.print("{");
            int cnt = 0, flag = 0;
            while(n != 0) {
                if(n%2 == 1) {
                    if(flag != 0)
                        System.out.print(",");
                    System.out.print(" " + pow[cnt].toString());
                    flag = 1;
                }
                cnt ++;
                n = n/2;
            }
            System.out.println(" }");
        }
    }
}

台長: Morris
人氣(908) | 回應(0)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 不分類 | 個人分類: UVA |
此分類下一篇:[UVA][Java] 10925 - Krakovia
此分類上一篇:[UVA][Java] 10494 - If We Were a Child Again

是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入圖片中算式的結果(可能為0) 
(有*為必填)
TOP
詳全文