给定两个整数和 ,任务是找到[1,n]范围内的所有数字之和,不包括k的正幂数,即k,k 2 ,k 3等。
例子:
Input: n = 10, k = 3
Output: 43
1 + 2 + 4 + 5 + 6 + 7 + 8 + 10 = 43
3 and 9 are excluded as they are powers of 3
Input: n = 11, k = 2
Output: 52
方法:
- 存储第一个的总和变量中的自然数即sum =(n *(n + 1))/ 2 。
- 现在,对于……的每一个积极力量小于 ,从中减去 。
- 打印变量的值到底。
下面是上述方法的实现:
C++
// C++ program to find the sum of
// first n natural numbers which are
// not positive powers of k
#include
using namespace std;
// Function to return the sum of
// first n natural numbers which are
// not positive powers of k
int find_sum(int n, int k)
{
// sum of first n natural numbers
int total_sum = (n * (n + 1)) / 2;
int power = k;
while (power <= n) {
// subtract all positive powers
// of k which are less than n
total_sum -= power;
// next power of k
power *= k;
}
return total_sum;
}
// Driver code
int main()
{
int n = 11, k = 2;
cout << find_sum(n, k);
return 0;
}
Java
// Java program to find the sum of
// first n natural numbers which are
// not positive powers of k
import java.io.*;
class GFG {
// Function to return the sum of
// first n natural numbers which are
// not positive powers of k
static int find_sum(int n, int k)
{
// sum of first n natural numbers
int total_sum = (n * (n + 1)) / 2;
int power = k;
while (power <= n) {
// subtract all positive powers
// of k which are less than n
total_sum -= power;
// next power of k
power *= k;
}
return total_sum;
}
// Driver code
public static void main (String[] args) {
int n = 11, k = 2;
System.out.println(find_sum(n, k));
}
}
// This code is contributed by inder_verma..
Python3
# Python 3 program to find the sum of
# first n natural numbers which are
# not positive powers of k
# Function to return the sum of
# first n natural numbers which are
# not positive powers of k
def find_sum(n, k):
# sum of first n natural numbers
total_sum = (n * (n + 1)) // 2
power = k
while power <= n:
# subtract all positive powers
# of k which are less than n
total_sum -= power
# next power of k
power *= k
return total_sum
# Driver code
n = 11; k = 2
print(find_sum(n, k))
# This code is contributed
# by Shrikant13
C#
// C# program to find the sum of
// first n natural numbers which are
// not positive powers of k
using System;
class GFG {
// Function to return the sum of
// first n natural numbers which are
// not positive powers of k
static int find_sum(int n, int k)
{
// sum of first n natural numbers
int total_sum = (n * (n + 1)) / 2;
int power = k;
while (power <= n) {
// subtract all positive powers
// of k which are less than n
total_sum -= power;
// next power of k
power *= k;
}
return total_sum;
}
// Driver code
public static void Main () {
int n = 11, k = 2;
Console.WriteLine(find_sum(n, k));
}
}
// This code is contributed by inder_verma..
PHP
Javascript
输出:
52