use crate::Solution;
use malachite::Natural;
use malachite::base::num::arithmetic::traits::Pow;
use malachite::rational::Rational;
use pmath::SimpleContinuedFraction;
problem!(Problem0080, 80, "Square Root Digital Expansion");
impl Solution for Problem0080 {
fn solve(&self) -> String {
let limit = Natural::from(10u8).pow(100);
let mut sum = 0;
for n in 1..=100 {
let cf = SimpleContinuedFraction::from_sqrt(n);
if cf.periodic().is_none() {
continue;
}
let mut last_convergent = Rational::from(1);
for c in cf.convergents() {
if last_convergent.denominator_ref() * c.denominator_ref() >= limit {
let (before_decimal, after_decimal) = c.digits(&Natural::const_from(10));
let i = before_decimal.len(); for d in before_decimal {
sum += i32::try_from(&d).unwrap();
}
for d in after_decimal.take(100 - i) {
sum += i32::try_from(&d).unwrap();
}
break;
} else {
last_convergent = c;
}
}
}
sum.to_string()
}
}