This page is still under construction.

Parts of this page are still being built. What you see may change.

Pyramid Sequence

Time limit1sMemory limit128 MB

Summary
Count the distinct pairs formed at matching positions of two repeating pyramid sequences of heights N and M.
Level

Medium7 of 10

Topics
Number theory, Math
Solved
No attempts yet

Problem

A pyramid sequence of height HH is 1,2,…,H−1,H,H−1,…,2,1,2,…1, 2, \dots, H-1, H, H-1, \dots, 2, 1, 2, \dots, so its first 2H−22H-2 elements repeat forever. A pyramid sequence of height 1 is 1 repeated forever.

Given two natural numbers NN and MM, pair up the elements that sit at the same position in the pyramid sequence of height NN and the pyramid sequence of height MM. Write a program that counts how many different pairs appear.

For N=3N = 3 and M=4M = 4 the two sequences start like this.

  • 1, 2, 3, 2, 1, 2, 3, 2, 1, 2, 3, 2, 1
  • 1, 2, 3, 4, 3, 2, 1, 2, 3, 4, 3, 2, 1

The different pairs are (1,1), (2,2), (3,3), (2,4), (1,3), (3,1), so there are 6 of them.

Input

The first line contains two natural numbers NN and MM separated by a space. (1≤N,M≤1091 \le N, M \le 10^9)

Output

Print the number of different pairs.

Hint

For N=3N = 3 and M=5M = 5 the two sequences start like this.

  • 1, 2, 3, 2, 1, 2, 3, 2, 1
  • 1, 2, 3, 4, 5, 4, 3, 2, 1

The different pairs are (1,1), (2,2), (3,3), (2,4), (1,5), so there are 5 of them.

Examples2

  1. Example 1

    Input
    3 5
    
    Expected output
    5
    
  2. Example 2

    Input
    3 4
    
    Expected output
    6