给定两个数字N和K ,任务是将K N表示为正好N个数字的总和。如果没有这样的数字,则打印NA 。
例子:
Input: N = 5, K = 2
Output: 2 2 4 8 16
Explanation:
2 + 2 + 4 + 8 + 16 = 32 = 25
Input: N = 4, K = 3
Output: 3 6 18 54
Explanation:
3 + 6 + 18 + 54 = 81 = 34
方法:为了获得数字,使它们的和为K的幂,我们可以选择满足以下条件的数字:
这将始终使总和为K的幂。
例如:这可以说明为:
Let N = 3 and K = 4.
We need to represent 43 (=64)
as the sum of exactly 3 numbers
According to the mentioned approach,
The 3 numbers which can be chosen are
(41) = 4
(42 - 41) = 16 - 4 = 12
(43 - 42) = 64 - 16 = 48
Adding the numbers = 4 + 12 + 48 = 64
which is clearly 43
Therefore the required 3 numbers
are 4, 12 and 48.
下面是上述方法的实现:
C++
// C++ program to represent K^N
// as the sum of exactly N numbers
#include
#define ll long long int
using namespace std;
// Function to print N numbers whose
// sum is a power of K
void print(ll n, ll k)
{
// Printing K ^ 1
cout << k << " ";
// Loop to print the difference of
// powers from K ^ 2
for (int i = 2; i <= n; i++) {
ll x = pow(k, i) - pow(k, i - 1);
cout << x << " ";
}
}
// Driver code
int main()
{
ll N = 3, K = 4;
print(N, K);
return 0;
}
Java
// Java program to represent K^N
// as the sum of exactly N numbers
import java.util.*;
class GFG{
// Function to print N numbers whose
// sum is a power of K
static void print(int n, int k)
{
// Printing K ^ 1
System.out.print(k+ " ");
// Loop to print the difference of
// powers from K ^ 2
for (int i = 2; i <= n; i++) {
int x = (int) (Math.pow(k, i) - Math.pow(k, i - 1));
System.out.print(x+ " ");
}
}
// Driver code
public static void main(String[] args)
{
int N = 3, K = 4;
print(N, K);
}
}
// This code is contributed by 29AjayKumar
Python 3
# Python 3 program to represent K^N
# as the sum of exactly N numbers
from math import pow
# Function to print N numbers whose
# sum is a power of K
def printf(n, k):
# Printing K ^ 1
print(int(k),end = " ")
# Loop to print the difference of
# powers from K ^ 2
for i in range(2, n + 1, 1):
x = pow(k, i) - pow(k, i - 1)
print(int(x),end= " ")
# Driver code
if __name__ == '__main__':
N = 3
K = 4
printf(N, K)
# This code is contributed by Surendra_Gangwar
C#
// C# program to represent K^N
// as the sum of exactly N numbers
using System;
class GFG{
// Function to print N numbers whose
// sum is a power of K
static void print(int n, int k)
{
// Printing K ^ 1
Console.Write(k+ " ");
// Loop to print the difference of
// powers from K ^ 2
for (int i = 2; i <= n; i++) {
int x = (int) (Math.Pow(k, i) - Math.Pow(k, i - 1));
Console.Write(x+ " ");
}
}
// Driver code
public static void Main(String[] args)
{
int N = 3, K = 4;
print(N, K);
}
}
// This code is contributed by Princi Singh
Javascript
输出:
4 12 48