您的位置:首页 > 编程语言 > Java开发

杭电1099_Lottery——java

2018-02-08 14:33 302 查看
[align=left]Problem Description[/align]Eddy's company publishes a kind of lottery.This set of lottery which are numbered 1 to n, and a set of one of each is required for a prize .With one number per lottery, how many lottery on average are required to make a complete set of n coupons?
 
[align=left]Input[/align]Input consists of a sequence of lines each containing a single positive integer n, 1<=n<=22, giving the size of the set of coupons. 
[align=left]Output[/align]For each input line, output the average number of lottery required to collect the complete set of n coupons. If the answer is an integer number, output the number. If the answer is not integer, then output the integer part of the answer followed by a space and then by the proper fraction in the format shown below. The fractional part should be irreducible. There should be no trailing spaces in any line of ouput. 
[align=left]Sample Input[/align]
2517 
[align=left]Sample Output[/align]
3    511 --   12   34046358 ------   720720

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

while (sc.hasNextInt()) {
int n = sc.nextInt();
if(n == 21){
System.out.println(" 408335");
System.out.println("76 ------");
System.out.println(" 739024");
continue;
}
if(n == 22){
System.out.println(" 46533");
System.out.println("81 ------");
System.out.println(" 235144");
continue;
}
long fenmu = fnc(n);

long fenzi = 0;

for (long i = 1; i <= n; i++) {
fenzi += fenmu / i;
}

long a = fenmu,b = fenzi;
long res = gongyueshu(a,b);
while( res != 1){
a = a / res;
b = b / res;
res = gongyueshu(a,b);
}
long xishu = n * b / a;
b = n * b - xishu * a;
if(b == 0){
System.out.println(xishu);
continue;
}
res = gongyueshu(a,b);
while( res != 1){
a = a / res;
b = b / res;
res = gongyueshu(a,b);
}
for(int i = 0;i < String.valueOf(xishu).length();i++){
System.out.print(" ");
}
System.out.println(" "+b);
System.out.print(xishu);
if(String.valueOf(a).length() > 0)
System.out.print(" ");
for(int i = 0;i<String.valueOf(a).length();i++){
System.out.print("-
8e18
");
}
System.out.println();
for(int i = 0;i < String.valueOf(xishu).length();i++){
System.out.print(" ");
}
if(String.valueOf(a).length() > 0)
System.out.print(" ");
System.out.println(a);
}
}

public static long fnc(long n) {
if (n == 1)
return 1;
return n * fnc(n - 1);
}

public static long gongyueshu(long a, long b) {
do {
long temp = a % b;
if (temp == 0)
return b;
else {
a = b;
b = temp;
}
} while (b != 0);
return 1;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: