logo AlgoBeat OnlineJudge
登录 注册

#209125. [SDCPC 2023] Math Problem

内存限制:1024 MiB 时间限制:4000 ms 标准输入输出
题目类型:VJudge(洛谷) 评测方式:VJudge
上传者: 匿名

题目描述

Given two positive integers and , you can perform the following two types of operations any number of times (including zero times):

  • Choose an integer which satisfies , and change into . It will cost you coins to perform this operation once. The integer you choose each time can be different.
  • Change into . It will cost you coins to perform this operation once. Note that is the largest integer which is less than or equal to .

Given a positive integer , calculate the minimum number of coins needed to change into a multiple of . Please note that is a multiple of any positive integer.

输入格式

There are multiple test cases. The first line of the input contains an integer () indicating the number of test cases. For each test case:

The first line contains five integers , , , , (, ).

输出格式

For each test case output one line containing one integer, indicating the minimum number of coins needed to change into a multiple of . If this goal cannot be achieved, output instead.

样例

样例输入 1

4
101 4 207 3 5
8 3 16 100 1
114 514 19 19 810
1 1 3 1 1

样例输出 1

11
2
0
-1

数据范围与提示

For the first sample test case, initially . The optimal steps are shown as follows:

  • Firstly, perform the second type of operation once. Change into . This step costs coins.
  • Then, perform the first type of operation once. Choose and change into . This step costs coins.
  • Then, perform the first type of operation once. Choose and change into . This step costs coins.
  • As , is a multiple of . The total cost is coins.

For the second sample test case, perform the second type of operation twice will change into . The total cost is coins.

For the third sample test case, as is already a multiple of , no operation is needed. The total cost is coins.