use crate::traits::{FftParameters, Field};
pub trait FftField: Field + From<u128> + From<u64> + From<u32> + From<u16> + From<u8> {
type FftParameters: FftParameters;
fn two_adic_root_of_unity() -> Self;
fn large_subgroup_root_of_unity() -> Option<Self>;
fn multiplicative_generator() -> Self;
fn get_root_of_unity(n: usize) -> Option<Self> {
let mut omega: Self;
if let Some(large_subgroup_root_of_unity) = Self::large_subgroup_root_of_unity() {
let q = Self::FftParameters::SMALL_SUBGROUP_BASE
.expect("LARGE_SUBGROUP_ROOT_OF_UNITY should only be set in conjunction with SMALL_SUBGROUP_BASE")
as usize;
let small_subgroup_base_adicity = Self::FftParameters::SMALL_SUBGROUP_BASE_ADICITY.expect(
"LARGE_SUBGROUP_ROOT_OF_UNITY should only be set in conjunction with SMALL_SUBGROUP_BASE_ADICITY",
);
let q_adicity = Self::k_adicity(q, n);
let q_part = q.pow(q_adicity);
let two_adicity = Self::k_adicity(2, n);
let two_part = 1 << two_adicity;
if n != two_part * q_part
|| (two_adicity > Self::FftParameters::TWO_ADICITY)
|| (q_adicity > small_subgroup_base_adicity)
{
return None;
}
omega = large_subgroup_root_of_unity;
for _ in q_adicity..small_subgroup_base_adicity {
omega = omega.pow([q as u64]);
}
for _ in two_adicity..Self::FftParameters::TWO_ADICITY {
omega.square_in_place();
}
} else {
let size = n.checked_next_power_of_two()? as u64;
let log_size_of_group = size.trailing_zeros();
if n != size as usize || log_size_of_group > Self::FftParameters::TWO_ADICITY {
return None;
}
omega = Self::two_adic_root_of_unity();
for _ in log_size_of_group..Self::FftParameters::TWO_ADICITY {
omega.square_in_place();
}
}
Some(omega)
}
fn k_adicity(k: usize, mut n: usize) -> u32 {
let mut r = 0;
while n > 1 {
if n % k == 0 {
r += 1;
n /= k;
} else {
return r;
}
}
r
}
}