Problem:
Score : 300 points

Problem Statement

You are given four integers A, B, C, and D. Find the number of integers between A and B (inclusive) that can be evenly divided by neither C nor D.

Constraints

1\leq A\leq B\leq 10^{18}

1\leq C,D\leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C D

Output

Print the number of integers between A and B (inclusive) that can be evenly divided by neither C nor D.

Sample Input 1

4 9 2 3

Sample Output 1

2

5 and 7 satisfy the condition.

Sample Input 2

10 40 6 8

Sample Output 2

23

Sample Input 3

314159265358979323 846264338327950288 419716939 937510582

Sample Output 3

532105071133627368

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

fn read_line() -> String {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    s.trim_right().to_owned()
}

fn div_n(source: u64, n: u64) -> Option<(u64, u64)> {
    let mut x = source;
    let mut count = 0;
    while x % n == 0 {
        x /= n;
        count += 1;
    }
    
    if count == 0 { None } else { Some((x, count)) }
}

fn factorize(source: u64) -> Vec<u64> {
    let mut x = source;
    let mut v = Vec::new();

    if let Some((divided, count)) = div_n(source, 2) {
        x = divided;
        v.extend(vec![2; count as usize]);
    }

    let mut i = 3;
    while (x / 3 + 3) > i {
        if let Some((divided, count)) = div_n(x, i) {
            x = divided;
            v.extend(vec![i; count as usize]);
        }
        i += 2;
    }
    
    if i != 1 {
        v.push(x);
    }
    v
}

fn least_common_multiple(a: u64, b: u64) -> u64 {
    let afs = factorize(a);
    let mut bfs = factorize(b);

    let mut x = 1;
    for af in afs {
        x *= af;
        if let Some(bf_index) = bfs.iter().position(|&bf| bf == af) {
            bfs.remove(bf_index);
        }
    }
    
    bfs.into_iter().fold(x, |total, bf| total * bf)
}

fn main() {
    let v: Vec<u64> = read_line().split_whitespace().map(|x| x.parse().unwrap()).collect();
    let (a, b, c, d) = (v[0], v[1], v[2], v[3]);
    let len = b - a + 1;
    let offset_c = (a - 1) % c;
    let offset_d = (a - 1) % d;
    let lcm = least_common_multiple(c, d);
    let offset_lcm = (a - 1) % lcm;
    
    let c_count = (len + offset_c) / c;
    let d_count = (len + offset_d) / d;
    let lcm_count = (len + offset_lcm) / lcm;
    println!("{}", len - (c_count + d_count - lcm_count));
}