Problem:
Score : 1000 points

Problem Statement

Takahashi and Aoki are going to together construct a sequence of integers.

First, Takahashi will provide a sequence of integers a, satisfying all of the following conditions:

The length of a is N.

Each element in a is an integer between 1 and K, inclusive.

a is a palindrome, that is, reversing the order of elements in a will result in the same sequence as the original.

Then, Aoki will perform the following operation an arbitrary number of times:

Move the first element in a to the end of a.

How many sequences a can be obtained after this procedure, modulo 10^9+7?

Constraints

1≤N≤10^9

1≤K≤10^9

Input

The input is given from Standard Input in the following format:

N K

Output

Print the number of the sequences a that can be obtained after the procedure, modulo 10^9+7.

Sample Input 1

4 2

Sample Output 1

6

The following six sequences can be obtained:

(1, 1, 1, 1)

(1, 1, 2, 2)

(1, 2, 2, 1)

(2, 2, 1, 1)

(2, 1, 1, 2)

(2, 2, 2, 2)

Sample Input 2

1 10

Sample Output 2

10

Sample Input 3

6 3

Sample Output 3

75

Sample Input 4

1000000000 1000000000

Sample Output 4

875699961

Solution in Rust (1.42.0) (judge verdict: Accepted)


use std::{cmp::{max, min, Reverse}, collections::{BTreeMap, BTreeSet, VecDeque, BinaryHeap} };

fn read_line() -> String {
    let mut buffer = String::new();
    std::io::stdin().read_line(&mut buffer).expect("No Line");
    buffer
}
fn read_lines<R, T: Fn(&str)->R> (count: usize, transformer: T) -> Vec<R> {
    let mut buffer = String::new();
    let mut vec = Vec::with_capacity(count);
    for _ in 0 .. count {
        std::io::stdin().read_line(&mut buffer).expect("No Line");
        vec.push(transformer(buffer.trim()));
    }
    vec
}
fn read_value<T: std::str::FromStr>() -> T {
    read_line().trim().parse().ok().unwrap()
}
fn read_values<T: std::str::FromStr>() -> Vec<T> {
    read_line().trim().split(' ').map(|x| x.parse().ok().expect("Can't Parse")).collect::<Vec<T>>()
}
fn read_tabulate<T: std::str::FromStr>(count: usize) -> Vec<T> {
    let mut buffer = String::new();
    let mut vec = Vec::with_capacity(count);
    for _ in 0 .. count {
        std::io::stdin().read_line(&mut buffer).expect("No Line");
        vec.push(buffer.parse().ok().expect("Can't Parse"));
    }
    vec
}
macro_rules! assign {
    () => {};
    ($($token:tt)*) => {
        let mut iter = read_values::<String>().into_iter();
        assign_iter!(iter, $($token)*);
    };
}
macro_rules! assign_iter {
    ($iter:expr) =>{};
    ($iter:expr,) =>{};
    ($iter:expr, $id:ident:$t:tt $($tail:tt)*) => {
        let $id: $t = $iter.next().unwrap().parse().ok().expect("Can't Parse");
        assign_iter!($iter, $($tail)*);
    };
    ($iter:expr, mut $id:ident:$t:tt $($tail:tt)*) => {
        let mut $id: $t = $iter.next().unwrap().parse().ok().expect("Can't Parse");
        assign_iter!($iter, $($tail)*)
    };
}
macro_rules! freeze {
    ($($id:ident), *) => {
        $(let $id = $id;)*
    };
}
struct KeyValue<K, V>{
    key: K, 
    value: V
}
impl <K: Clone, V: Clone> Clone for KeyValue<K, V> {
    fn clone(&self) -> Self {
        KeyValue{key: self.key.clone(), value: self.value.clone()}
    }
}
impl <K: PartialEq, V> PartialEq for KeyValue<K, V> {
    fn eq(&self, other: &Self) -> bool {
        self.key.eq(&other.key)
    }
}
impl <K: PartialEq, V> Eq for KeyValue<K, V> {}
impl <K: PartialOrd, V> PartialOrd for KeyValue<K, V> {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        self.key.partial_cmp(&other.key)
    }
}
impl <K: PartialOrd, V> Ord for KeyValue<K, V> {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        match self.key.partial_cmp(&other.key) {
            Some(r) => r,
            None => panic!("Can\'t Compare"),
        }
    }
}
fn pow_mod(base: i64, exp: usize, modulo: i64) -> i64 {
    match exp {
        0 => 1i64,
        1 => base % modulo,
        _ => pow_mod(base * base % modulo, exp >> 1, modulo) * pow_mod(base, exp & 1, modulo) % modulo
    }
}
fn main() {
    let MOD = 1000000007;
    assign!{
        n: i64
        k: i64
    }
    let mut p = 1i64;
    let mut divisor = Vec::new();
    while p * p <= n {
        if n % p == 0 {
            divisor.push(p);
            let other = n / p;
            if other != p {
                divisor.push(other);
            }
        }
        p += 1;
    }
    divisor.sort();
    let mut cycle_count = vec![0i64; divisor.len()];
    for i in 0usize .. divisor.len() {
        let d = divisor[i];
        let mut acc = pow_mod(k, ((d + 1) >> 1) as usize, MOD);
        for j in 0usize .. divisor.len() {
            let e = divisor[j];
            if e >= d {break;}
            if d % e == 0{
                acc = (acc - cycle_count[j] + MOD) % MOD;
            }
        }
        cycle_count[i] = acc; 
    }
    let mut sum = 0i64;
    for i in 0usize .. divisor.len() {
        let d = divisor[i];
        if (d & 1) == 0 {
            sum = (sum + cycle_count[i] * (d >> 1)) % MOD;
        }else {
            sum = (sum + cycle_count[i] * d) % MOD;
        }
    }
    println!("{}", sum);
}