Last active
June 4, 2017 05:41
-
-
Save nogitsune413/2845c3f6cb0212e7b89545f88813e02a to your computer and use it in GitHub Desktop.
有理数から循環小数を算出する。 [アルゴリズム]リストによる内部状態の保存、比較 (Scala)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.collection.immutable.Stream.Empty | |
/** | |
* 循環小数の検出 | |
* Created by nakam on 2017/05/14. | |
*/ | |
object DivideTest { | |
def main(args: Array[String]): Unit = { | |
val dividend = 9 // 割られる数 | |
val divisor = 74 // 割る数 | |
val limit = -1 // 小数点以下何桁まで計算を続けるか。制限を設けない場合は、-1。 | |
rationalNumberToRecurringDecimal(dividend, divisor,limit) | |
} | |
def rationalNumberToRecurringDecimal(dividend:Int, divisor:Int,limitNumberOfDigit:Int) : Unit = { | |
var currentDividend = dividend | |
var resultSummary : StringBuilder = new StringBuilder | |
var remaindersSeq:Seq[Int] = Seq() | |
var i = 0 | |
while(i <= limitNumberOfDigit || limitNumberOfDigit == -1){ | |
val result = currentDividend / divisor | |
val remainder = currentDividend % divisor | |
resultSummary ++= (if (i == 1) "." + result.toString else result.toString) | |
printf("小数部:%2d, 答:%d, 余り:%2d, 算出結果:%s%n",i,result,remainder,resultSummary) | |
if(remainder == 0) { | |
println("割り切れました。算出結果:" + resultSummary) | |
return | |
} else { | |
if(remaindersSeq.contains(remainder)){ | |
println("小数第" + i + "位で循環小数になったため、計算を終了します。") | |
println("循環節の開始位置は、小数第" + (remaindersSeq.indexOf(remainder) + 1) + "位です。") | |
return | |
} | |
remaindersSeq = remaindersSeq :+ remainder | |
currentDividend = remainder * 10 | |
} | |
i += 1 | |
} | |
println("小数部が" + limitNumberOfDigit + "桁に達したため、処理を終了します。") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment