Dirichlet's Theorem on Arithmetic Progressions

Time limit1sMemory limit128 MB

Summary
Count how many terms a*n+b in a given range of n are prime, with the terms reaching up to 10^12 and at most 10^6 values per case.
Level

Medium6 of 10

Topics
Number theory, Math, Implementation, Brute force
Solved
No attempts yet

Problem

Dirichlet's theorem on arithmetic progressions states that for two coprime positive integers aa and bb, the arithmetic progression t(n)=a⋅n+bt(n) = a \cdot n + b (n≥0n \ge 0) contains infinitely many primes.

A prime is a positive integer greater than 11 whose only divisors are 11 and itself.

For example, when a=4a = 4 and b=3b = 3, the progression is:

3, 7, 11, 15, 19, 23, 27, 31, 35, …3,\ 7,\ 11,\ 15,\ 19,\ 23,\ 27,\ 31,\ 35,\ \dots

Even just the beginning of this progression clearly contains many primes.

Given a positive integer a>0a > 0, an integer b≥0b \ge 0, and U≥L≥0U \ge L \ge 0, write a program that counts how many of the terms t(n)=a⋅n+bt(n) = a \cdot n + b for L≤n≤UL \le n \le U are prime.

Input

The input consists of several test cases. Each test case is a single line containing four integers aa, bb, LL, and UU. It is guaranteed that a⋅U+b≤1012a \cdot U + b \le 10^{12} and U−L≤106U - L \le 10^{6}. The last line contains a single 00, which marks the end of the input.

Output

For each test case, print one line in the format Case x: c, where xx is the test case number starting from 11 and cc is the number of terms t(n)t(n) that are prime for L≤n≤UL \le n \le U.

Examples3

  1. Example 1

    Input
    4 3 0 8
    1 0 2 100
    2 7 0 1000
    0
    
    Expected output
    Case 1: 6
    Case 2: 25
    Case 3: 301
    
  2. Example 2

    Input
    1 0 0 1
    0
    
    Expected output
    Case 1: 0
    
  3. Example 3

    Input
    1 2 0 0
    0
    
    Expected output
    Case 1: 1