📌  相关文章
📜  查找给定基数B中最多N个数字的总数

📅  最后修改于: 2021-04-27 19:44:06             🧑  作者: Mango

给定两个整数NB ,任务是找到最多N个数字的Base B的自然数。

例子:

方法:仔细观察以B为底的N位数字的计数是一个几何级数,第一个项为(B – 1),且公共比率为B。
所以,

最后,通过从1到N的循环迭代并使用上述公式计算第i项的总和,可以找出基数B中最多N个数字的所有自然数。

下面是上述方法的实现:

C++
// C++ implementation to find the count
// of natural numbers upto N digits
 
#include 
 
using namespace std;
 
// Function to return the count of
// natural numbers upto N digits
int count(int N, int B)
{
    int sum = 0;
 
    // Loop to iterate from 1 to N
    // and calculating number of
    // natural numbers for every 'i'th digit.
    for (int i = 1; i <= N; i++) {
        sum += (B - 1) * pow(B, i - 1);
    }
    return sum;
}
 
// Driver Code
int main()
{
    int N = 2, B = 10;
    cout << count(N, B);
 
    return 0;
}


Java
// Java implementation to find the count
// of natural numbers upto N digits
 
class GFG{
 
// Function to return the count of
// natural numbers upto N digits
static int count(int N, int B)
{
    int sum = 0;
 
    // Loop to iterate from 1 to N
    // and calculating number of
    // natural numbers for every 'i'th digit.
    for (int i = 1; i <= N; i++){
        sum += (B - 1) * Math.pow(B, i - 1);
    }
    return sum;
}
 
// Driver Code
public static void main(String[] args)
{
    int N = 2, B = 10;
    System.out.print(count(N, B));
}
}
 
// This code is contributed by gauravrajput1


Python3
# Python3 implementation to find the count
# of natural numbers up to N digits
 
from math import pow
 
# Function to return the count of
# natural numbers upto N digits
def count(N, B):
    sum = 0
 
    # Loop to iterate from 1 to N
    # and calculating number of
    # natural numbers for every 'i'th digit.
    for i in range(1, N+1):
        sum += (B - 1) * pow(B, i - 1)
    return sum
 
# Driver Code
if __name__ == '__main__':
    N = 2
    B = 10
    print(int(count(N, B)))
 
# This code is contributed by Bhupendra_Singh


C#
// C# implementation to find the count
// of natural numbers upto N digits
using System;
using System.Collections.Generic;
class GFG{
 
// Function to return the count of
// natural numbers upto N digits
static int count(int N, int B)
{
    int sum = 0;
 
    // Loop to iterate from 1 to N
    // and calculating number of
    // natural numbers for every
    // 'i'th digit.
    for(int i = 1; i <= N; i++)
    {
       sum += (int)((B - 1) * Math.Pow(B, i - 1));
    }
    return sum;
}
 
// Driver Code
public static void Main(String[] args)
{
    int N = 2, B = 10;
     
    Console.Write(count(N, B));
}
}
 
// This code is contributed by amal kumar choubey


Javascript


输出:
99

时间复杂度: O(N)