ALGO-33 数列
资源限制
时间限制:1.0s 内存限制:256.0MB
问题描述
给定一个正整数k(3≤k≤15),把所有k的方幂及所有有限个互不相等的k的方幂之和构成一个递增的序列,例如,当k=3时,这个序列是:
1,3,4,9,10,12,13,…
(该序列实际上就是:30,31,30+31,32,30+32,31+32,30+31+32,…)
请你求出这个序列的第N项的值(用10进制数表示)。
例如,对于k=3,N=100,正确答案应该是981。
输入格式
只有1行,为2个正整数,用一个空格隔开:
k N
(k、N的含义与上述的问题描述一致,且3≤k≤15,10≤N≤1000)
输出格式
计算结果,是一个正整数(在所有的测试数据中,结果均不超过2.1*109)。(整数前不要有空格和其他符号)
测试样例
输入:
3 100
输出:
981
AC code:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int K = sc.nextInt(), N = sc.nextInt();
int[] an = new int[N + 2];
an[0] = 1;
for (int offset = 0, k = 1; offset < N; an[++offset] = k *= K)
for (int i = 0, j = offset; i < j && offset < N; i++) an[++offset] = k + an[i];
System.out.print(an[N - 1]);
}
}
算是道找规律的题吧
把传统的指数递增数列分割开来,后面插入该元素与前面所有项对应的和
这种解法还可以写的 抽象一点:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int K = sc.nextInt(), N = sc.nextInt(), cnt = 0;
int[] an = new int[N + 2];
an[0] = 1;
for (int offset = 0, k = 1; offset < N; an[++offset] = k <<= 1)
for (int i = 0, j = offset; i < j && offset < N; i++) an[++offset] = k | an[i];
for (int i = an[N - 1], k = 1; i != 0; i >>>= 1, k *= K) if ((i & 1) == 1) cnt += k;
System.out.print(cnt);
}
}
用位来表示当前项是K指数递增序列的哪几项的和,性能只有微弱的提升
但是我们这个时候输出一下{ an }
这里我就不做数学证明,不会,我只能说不会
总之
这么写:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int cnt = 0;
for (int K = sc.nextInt(), N = sc.nextInt(), k = 1; N != 0; N >>>= 1, k *= K) if ((N & 1) == 1) cnt += k;
System.out.print(cnt);
}
}
就对了