练习cf1674A. Number Transformation
题目如下
A. Number Transformation
time limit per test2 seconds
memory limit per test512 megabytes
You are given two integers 𝑥 and 𝑦. You want to choose two strictly positive (greater than zero) integers 𝑎 and 𝑏, and then apply the following operation to 𝑥 exactly 𝑎 times: replace 𝑥 with 𝑏⋅𝑥.
You want to find two positive integers 𝑎 and 𝑏 such that 𝑥 becomes equal to 𝑦 after this process. If there are multiple possible pairs, you can choose any of them. If there is no such pair, report it.
For example:
if 𝑥=3 and 𝑦=75, you may choose 𝑎=2 and 𝑏=5, so that 𝑥 becomes equal to 3⋅5⋅5=75;
if 𝑥=100 and 𝑦=100, you may choose 𝑎=3 and 𝑏=1, so that 𝑥 becomes equal to 100⋅1⋅1⋅1=100;
if 𝑥=42 and 𝑦=13, there is no answer since you cannot decrease 𝑥 with the given operations.
Input
The first line contains one integer 𝑡 (1≤𝑡≤104) — the number of test cases.
Each test case consists of one line containing two integers 𝑥 and 𝑦 (1≤𝑥,𝑦≤100).
Output
If it is possible to choose a pair of positive integers 𝑎 and 𝑏 so that 𝑥 becomes 𝑦 after the aforementioned process, print these two integers. The integers you print should be not less than 1 and not greater than 109 (it can be shown that if the answer exists, there is a pair of integers 𝑎 and 𝑏 meeting these constraints). If there are multiple such pairs, print any of them.
If it is impossible to choose a pair of integers 𝑎 and 𝑏 so that 𝑥 becomes 𝑦, print the integer 0 twice.
题目大意
现有x,y,能否找出任意a,b,使得x * (b^a)= y;如果有就输出a,b的值,否则输出“0 0”。
题目分析
根据x * (b^a)= y,可以得到 b^a = y / x,所以可以通过暴力遍历得出a和b的值。
首先要判断x,y是否满足条件;
点击查看代码
if(y < x || y % x != 0){
printf("0 0\n");
}else if(y == x){
printf("1 1\n");
}else{
int n = y / x;
int a = 0, b = 0;
if(check(n, &a, &b)){
printf("%d %d\n", a, b);
}else{
printf("0 0\n");
}
}
点击查看代码
int check(int n, int* aa, int* bb){
for(int b = 2; b * b <= n; b++){
long long power = b;
int a = 1;
while(power <= n){
if(power == n){
*aa = a;
*bb = b;
return 1;
}
power *= b;
a++;
}
}
for(int b = 2; b <= n; b++){
if(b == n){
*aa = 1;
*bb = b;
return 1;
}
}
return 0;
}
完整代码
点击查看代码
#include <stdio.h>
int check(int n, int* aa, int* bb){
for(int b = 2; b * b <= n; b++){
long long power = b;
int a = 1;
while(power <= n){
if(power == n){
*aa = a;
*bb = b;
return 1;
}
power *= b;
a++;
}
}
for(int b = 2; b <= n; b++){
if(b == n){
*aa = 1;
*bb = b;
return 1;
}
}
return 0;
}
int main(){
int t;
scanf("%d", &t);
while(t--){
int x, y;
scanf("%d%d", &x, &y);
if(y < x || y % x != 0){
printf("0 0\n");
}else if(y == x){
printf("1 1\n");
}else{
int n = y / x;
int a = 0, b = 0;
if(check(n, &a, &b)){
printf("%d %d\n", a, b);
}else{
printf("0 0\n");
}
}
}
return 0;
}

浙公网安备 33010602011771号