📌  相关文章
📜  查找仅可以使用数字3、4形成且长度最大为N的数字计数。

📅  最后修改于: 2021-04-26 06:16:55             🧑  作者: Mango

给定数字N。找到仅可以使用数字3和4形成且长度最大为N的此类数字的计数。
例子:

Input : N = 2
Output : 6
Explanation : 3, 4, 33, 34, 43, 44 
are numbers having length 2 and digits 3 and 4 only.

Input : N = 1
Output : 2
Explanation : 3, 4 are the only such numbers.

方法:有2个长度为1的数字。它们是3和4。有4个长度为2的数字。它们分别是33、34、43和44。有8个这样的长度为3的数字。它们分别是333、334、343 ,344、433、434、443、444。长度每增加1,数字的数量就会增加2倍。
很容易证明:对于前一个长度的任意数量,可以附加3或4,因此前一个长度的一个数量将创建下一个长度的两个。
因此,对于长度N,长度恰好为N的此类数的数量为2 * N。但是在问题中,我们需要长度不大于N的数量。让我们对其进行总结。 2 1 = 2、2 1 + 2 2 = 2 + 4 = 6、2 1 + 2 2 + 2 3 = 2 + 4 + 8 = 14、2 1 + 2 2 + 2 3 + 2 4 = 2 + 4 + 8 + 16 = 30。
可以注意到,所有先前的2的幂之和等于2的下一个幂减去2的第一个幂。因此,问题的答案是2 N + 1 – 2。
下面是上述方法的实现:

C++
// Cpp program to find the count of numbers that
// can be formed using digits 3, 4 only and
// having length at max N.
#include 
using namespace std;
 
// Function to find the count of numbers that
// can be formed using digits 3, 4 only and
// having length at max N.
long long numbers(int n)
{
    return (long long)(pow(2, n + 1)) - 2;
}
 
// Driver code
int main()
{
    int n = 2;
 
    cout << numbers(n);
 
    return 0;
}


Java
// Java program to find the count of numbers that
// can be formed using digits 3, 4 only and
// having length at max N.
 
class GFG
{
     
// Function to find the count of numbers that
// can be formed using digits 3, 4 only and
// having length at max N.
static long numbers(int n)
{
    return (long)(Math.pow(2, n + 1)) - 2;
}
 
// Driver code
public static void main(String args[])
{
    int n = 2;
 
    System.out.println( numbers(n));
}
}
 
// This code is contributed by Arnab Kundu


Python3
# Python3 program to find the count of
# numbers that can be formed using digits
# 3, 4 only and having length at max N.
 
# Function to find the count of numbers
# that can be formed using digits 3, 4
# only and having length at max N.
def numbers(n):
    return pow(2, n + 1) - 2
 
# Driver code
n = 2
print(numbers(n))
 
# This code is contributed
# by Shrikant13


C#
// C# program to find the count of numbers that
// can be formed using digits 3, 4 only and
// having length at max N.
using System;
 
class GFG
{
     
// Function to find the count of numbers that
// can be formed using digits 3, 4 only and
// having length at max N.
static long numbers(int n)
{
    return (long)(Math.Pow(2, n + 1)) - 2;
}
 
// Driver code
static void Main()
{
    int n = 2;
 
    Console.WriteLine( numbers(n));
}
}
 
// This code is contributed by mits


PHP


Javascript


输出:
6