📜  八进制数(最多N位)的计数

📅  最后修改于: 2021-05-07 01:14:58             🧑  作者: Mango

给定整数N ,任务是查找最多N个数字的自然八进制数的计数。

方法:仔细观察,就形成了一个几何级数级数[ 7 56 448 3584 28672 229376… ],第一项为7 ,共同比率为8
所以,

Nth term = Number of Octal numbers of N digits = 7 * 8N - 1

最后,通过从1到N的循环迭代并使用上述公式计算第i个项的总和,可以找到最多N个数字的所有八进制数的计数。
下面是上述方法的实现:

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


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


Python3
# Python3 program to find the count of
# natural octal numbers upto N digits
 
# Function to return the count of
# natural octal numbers upto N digits
def count(N) :
 
    sum = 0;
 
    # Loop to iterate from 1 to N
    # and calculating number of
    # octal numbers for every 'i'th digit.
    for i in range(N + 1) :
        sum += 7 * (8 **(i - 1));
     
    return int(sum);
 
# Driver code
if __name__ == "__main__" :
 
    N = 4;
    print(count(N));
 
# This code is contributed by AnkitRai01


C#
// C# program to find the count of
// natural octal numbers upto N digits
using System;
 
class GFG
{
     
    // Function to return the count of
    // natural octal numbers upto N digits
    static int count(int N)
    {
        int sum = 0;
     
        // Loop to iterate from 1 to N
        // and calculating number of
        // octal numbers for every 'i'th digit.
        for (int i = 1; i <= N; i++)
        {
            sum += (int)(7 * Math.Pow(8, i - 1));
        }
        return sum;
    }
     
    // Driver code
    public static void Main ()
    {
        int N = 4;
        Console.WriteLine(count(N));
    }
}
 
// This code is contributed by AnkitRai01


Javascript


输出:
4095

时间复杂度: O(N)