天天看點

java實作 洛谷 P1014 Cantor表

題目描述

現代數學的著名證明之一是Georg Cantor證明了有理數是可枚舉的。他是用下面這一張表來證明這一命題的:

1/1 1/2 1/3 1/4 1/5 …

2/1 2/2 2/3 2/4 …

3/1 3/2 3/3 …

4/1 4/2 …

5/1 …

… 我們以Z字形給上表的每一項編号。第一項是1/1,然後是1/2,2/1,3/1,2/2,…

輸入輸出格式

輸入格式:

整數N(1≤N≤10000000)

輸出格式:

表中的第N項

輸入輸出樣例

輸入樣例#1:

7

輸出樣例#1:

1/4

做樹狀數組WA到飛起,做一道找規律的水題調解心情……


```
import java.util.Scanner;
 
public class Main {
	private static Scanner cin;
	
	public static void main(String args[]) throws Exception {
		cin = new Scanner(System.in);
		int n = cin.nextInt();
		int count = 0;
		for(int i=1;i<=n;i++) {
			if(count<n &&(count+i)>=n) {
				for(int j=1;j<=i;j++) {
				 if((count+j) == n) {
					 if(i%2==0) {
						 System.out.println(String.format("%d/%d", j,i-j+1));
						 return;
					 }else {
						 System.out.println(String.format("%d/%d",i-j+1, j));
						 return;
					 }
				 }
				}
			}else {
				count = count + i;
			}
		}
	}
}
```