演算法競賽入門-迴圈小數(Repeating Decimals)
阿新 • • 發佈:2019-02-15
1、題目
輸入整數a(0<=a<=3000)和 b (1<=b<=3000),輸出a/b的迴圈小數表示以及迴圈位元組長度。例如a=5,b=43,小數表示為0.(116279069767441860465),迴圈位元組長度為21。
2、思路
第一步:先算出 a/b 的 商
第二步:算出 a%b 的餘數
第三步:迴圈計算 (餘數遠遠小於除數,所以需要將餘數擴大10倍,然後再被除數相除,然後迴圈)
3、程式碼
package basic.第三章; import java.util.Scanner; /** * 迴圈小數(Repeating Decimals) * 題目: * 輸出a/b的迴圈小數表示以及迴圈節長度 * Created by Administrator on 2018/4/12. * <p> * 第一步:先算出 a/b 的 商 * 第二步:算出 a%b 的餘數 * 第三步:迴圈計算 (餘數遠遠小於除數,所以需要將餘數擴大10倍,然後再被除數相除,然後迴圈) * * @author 春風吹又生 */ public class RepeatingDecimals { static int[] arr = new int[3000]; // 用來儲存餘數 static int[] tep = new int[3000]; // 用來儲存被除數 public static void main(String[] args) { Scanner read = new Scanner(System.in); int a = read.nextInt(); int b = read.nextInt(); int x = a / b; int temp = a % b * 10; int index = 0; while (tep[temp] == 0) { // 如果被除數沒有重複 int yu = temp / b; tep[temp] = 1; arr[index++] = yu; temp = temp % b * 10; } System.out.print(x+".("); for (int i = 0; i < index; i++) { System.out.print(arr[i]); } System.out.println(")"); System.out.println(index); } }
經提示,以上程式碼有問題,不能正確完成。經檢視除錯,沒有考慮有一些資料時非迴圈的。解決方案是:在迴圈計算小數點的資料時,採用一個temp變數來儲存當前位數,當迴圈結束也就是找到迴圈小節的時候,根據temp變數可以得到非迴圈的小數,也就是小於temp的之前的數為非迴圈小節。
package basic.第三章; import java.util.Scanner; /** * 迴圈小數(Repeating Decimals) * 題目: * 輸出a/b的迴圈小數表示以及迴圈節長度 * Created by Administrator on 2018/4/12. * <p> * 第一步:先算出 a/b 的 商 * 第二步:算出 a%b 的餘數 * 第三步:迴圈計算 (餘數遠遠小於除數,所以需要將餘數擴大10倍,然後再被除數相除,然後迴圈) * * @author 春風吹又生 */ public class RepeatingDecimals { static int[] arr = new int[3000 + 5]; static int[] tep = new int[3000 + 5]; public static void main(String[] args) { Scanner read = new Scanner(System.in); int a = read.nextInt(); int b = read.nextInt(); // 得商 int x = a / b; // 得餘數 int temp = a % b; // temp變數用於標記迴圈小數的開始, 在temp之前的都不是迴圈小數 // 得到剩餘待除 a = a % b * 10; int index = 0; while (tep[temp] == 0) { // 如果當前的餘數沒有相同的 int yu = a / b; // 得商 arr[++index] = yu; // 儲存該商 tep[temp] = index; // 儲存餘數的下標 temp = a % b; // 得餘數 a = a % b * 10; // 得到剩餘待除 } //arr[1]=1 arr[2]=6 //temp[1]= 1 temp[4]=2 //temp=4 index=2 System.out.print(x + "."); if (a == 0) {// 如果被整除 for (int i = 1; i < index; i++) System.out.print(arr[i]); System.out.println("(0)"); System.out.println(1); return; } // 如果沒有整除 for (int i = 1; i < tep[temp]; i++) { // 在之前的不是迴圈小數 System.out.print(arr[i]); } System.out.print("("); for (int i = tep[temp]; i <= index && i <= tep[temp] + 100; i++) { System.out.print(arr[i]); } System.out.println(")"); System.out.println(index - tep[temp] + 1); } }