use super::dense::{identity, mul};
use crate::domain::scalar::Scalar;
use leto::{Array2, ArrayView2, LetoError, Result};
pub fn matpow<T: Scalar>(matrix: &ArrayView2<'_, T>, exponent: u32) -> Result<Array2<T>> {
let [rows, cols] = matrix.shape();
if rows != cols {
return Err(LetoError::ShapeMismatch {
lhs: vec![rows, cols],
rhs: vec![rows, rows],
});
}
let mut result = identity::<T>(rows); if exponent == 0 {
return Ok(result);
}
let mut base = matrix.to_contiguous(); let mut remaining = exponent;
loop {
if remaining & 1 == 1 {
result = mul(&result.view(), &base.view())?;
}
remaining >>= 1;
if remaining == 0 {
break;
}
base = mul(&base.view(), &base.view())?; }
Ok(result)
}