不同的幂
考虑所有满足2 ≤ a ≤ 5和2 ≤ b ≤ 5的整数组合生成的幂ab:
22=4, 23=8, 24=16, 25=32
32=9, 33=27, 34=81, 35=243
42=16, 43=64, 44=256, 45=1024
52=25, 53=125, 54=625, 55=3125
如果把这些幂按照大小排列并去重,我们得到以下由15个不同的项组成的序列:
4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125
在所有满足2 ≤ a ≤ 100和2 ≤ b ≤ 100的整数组合生成的幂ab排列并去重所得到的序列中,有多少个不同的项?
代码演示
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
#define MAX_N 100
struct Data {
int cnt, p[5], a[5];
int i, j;
} arr[MAX_N * MAX_N];
int cnt = 0;
bool same(Data &a, Data &b) {
if (a.cnt != b.cnt) return false;
for (int i = 0; i < a.cnt; i++) {
if (a.p[i] != b.p[i] || a.a[i] != b.a[i]) return false;
}
return true;
}
void add(int a, int b) {
Data temp;
temp.cnt = 0;
temp.i = a, temp.j = b;
int i = 2;
while (a != 1) {
if (a % i == 0) {
temp.p[temp.cnt] = i;
temp.a[temp.cnt] = 0;
while (a % i == 0) a /= i, temp.a[temp.cnt] += 1;
temp.cnt += 1;
}
i += 1;
}
for (int i = 0; i < temp.cnt; i++) temp.a[i] *= b;
for (int i = 0; i < cnt; i++) {
if (!same(temp, arr[i])) continue;
return ;
}
memcpy(arr + cnt, &temp, sizeof(temp));
cnt += 1;
return ;
}
bool cmp(const Data &a, const Data &b) {
return a.j * log10(a.i) < b.j * log10(b.i);
}
int main() {
for (int i = 2; i <= MAX_N; i++) {
for (int j = 2; j <= MAX_N; j++) {
add(i, j);
}
}
sort(arr, arr + cnt, cmp);
for (int i = 0; i < cnt; i++) {
printf("%d ^ %d\n", arr[i].i, arr[i].j);
}
cout << cnt << endl;
return 0;
}