[Blue Bridge Cup] k-base number

[Blue Bridge Cup] k-base number

Subject link: https://www.dotcpp.com/oj/problem1117.html

Ideas:

Conditions for valid numbers: ① The first digit of the valid digits cannot be 0, ② There can be no consecutive 0s in the valid digits, and ③ The digits of the k-ary system can only be 0~k-1.

  • First, suppose that N = 1, that is, there is only one digit, and the total number of valid k bases it contains is 1, 2, 3,..., k-1, a total of k-1 valid digits, let res1 represent this k- 1 bit, res1=k-1, res0 represents the number of cases that cannot be 0 is 1, res0=1.
  • Then suppose N = 2, when there are two digits, the second digit from right to left can be 1, 2, 3,..., k-1, a total of k-1 digits, counting from right to left The first digit can be 1~k-1 or 0, so it is combined with these k-1+1 cases, the effective number when N = 2 is (k-1) * [(k-1) +1 ], so the number of significant digits is res1= (k-1) * [(k-1) +1 ], because the first digit cannot be 0, so res0=k-1.
  • When N=3, the third digit from right to left can be 1, 2, 3,..., k-1, so res1=(k-1) * {(k-1) * [(k- 1) +1]}, the first digit cannot be 0, so res0= (k-1) * [(k-1) +1]

State the law:

[N = the number of significant digits of i] is equal to [k-1] multiplied by [When N = i-1: the number of significant digits + the number when the highest digit cannot be 0]

[The number when the highest bit of N=i cannot be 0] is equal to [when N=i-1: the number of significant digits]

Insert picture description here
Insert picture description here

Analysis diagram:
Insert picture description here

撸Code:

#include<stdio.h>
int main()
{
    
    
	long long n,k;
	scanf("%lld%lld",&n,&k);
	long long res1=k-1,res0=1;
	for(int i=2;i<=n;i++){
    
    
		int temp=res1;
		res1=(k-1)*(res1+res0);
		res0=temp;
	}
	printf("%lld\n",res1);
	return 0;
}

The solution is learned from: https://blog.csdn.net/qq_41923622/article/details/85207046

Guess you like

Origin blog.csdn.net/DREAM_yao/article/details/109037081