Números con una diferencia de Fibonacci entre Suma de dígitos en posiciones pares e impares en un rango dado

Prerrequisitos: Dígito DP Dado un rango [L, R] , la tarea es contar los números en este rango que tienen la diferencia entre la suma de dígitos en posiciones pares y la suma de dígitos en posiciones impares, como un número de Fibonacci. Nota: Considere la posición del dígito menos significativo en el número como una posición impar. Ejemplos:

Entrada: L = 1, R = 10 Salida: 1 Explicación: El único número que satisface la condición dada es 10. Entrada: L = 50, R = 100 Salida: 27

Enfoque: La idea es utilizar el concepto de Programación Dinámica para resolver este problema. El concepto de dígito dp se usa para formar una tabla DP .

  • Se forma una tabla de cuatro dimensiones y en cada llamada recursiva , debemos verificar si la diferencia requerida es un número de Fibonacci o no.
  • Dado que el número más alto en el rango es 10 18 , la suma máxima en posiciones pares o impares puede ser un máximo de 9 veces 9 y, por lo tanto, la diferencia máxima. Por lo tanto, debemos verificar solo los números de Fibonacci hasta 100 en la condición base.
  • Para verificar si el número es Fibonacci o no, genere todos los números de Fibonacci y cree un conjunto hash .

Los siguientes son los estados DP de la tabla:

  • Dado que podemos considerar nuestro número como una secuencia de dígitos, un estado es la posición en la que nos encontramos actualmente. Esta posición puede tener valores del 0 al 18 si se trata de números hasta el 10 18 . En cada llamada recursiva, tratamos de construir la secuencia de izquierda a derecha colocando un dígito del 0 al 9.
  • El primer estado es la suma de los dígitos en las posiciones pares que hemos colocado hasta ahora.
  • El segundo estado es la suma de los dígitos en posiciones impares que hemos colocado hasta ahora.
  • Otro estado es la variable booleana tight que indica que el número que estamos tratando de construir ya se ha vuelto más pequeño que R, de modo que en las próximas llamadas recursivas podemos colocar cualquier dígito del 0 al 9. Si el número no se ha vuelto más pequeño, el límite máximo de dígito que podemos colocar en la posición actual en R.

A continuación se muestra la implementación del enfoque anterior: 

C++

// C++ program to count the numbers in
// the range having the difference
// between the sum of digits at even
// and odd positions as a Fibonacci Number
 
#include <bits/stdc++.h>
using namespace std;
 
const int M = 18;
int a, b, dp[M][90][90][2];
 
// To store all the
// Fibonacci numbers
set<int> fib;
 
// Function to generate Fibonacci
// numbers upto 100
void fibonacci()
{
    // Adding the first two Fibonacci
    // numbers in the set
    int prev = 0, curr = 1;
    fib.insert(prev);
    fib.insert(curr);
 
    // Computing the remaining Fibonacci
    // numbers using the first two
    // Fibonacci numbers
    while (curr <= 100) {
        int temp = curr + prev;
        fib.insert(temp);
        prev = curr;
        curr = temp;
    }
}
 
// Function to return the count of
// required numbers from 0 to num
int count(int pos, int even,
          int odd, int tight,
          vector<int> num)
{
    // Base Case
    if (pos == num.size()) {
        if (num.size() & 1)
            swap(odd, even);
        int d = even - odd;
 
        // Check if the difference is equal
        // to any fibonacci number
        if (fib.find(d) != fib.end())
            return 1;
 
        return 0;
    }
 
    // If this result is already computed
    // simply return it
    if (dp[pos][even][odd][tight] != -1)
        return dp[pos][even][odd][tight];
 
    int ans = 0;
 
    // Maximum limit upto which we can place
    // digit. If tight is 1, means number has
    // already become smaller so we can place
    // any digit, otherwise num[pos]
    int limit = (tight ? 9 : num[pos]);
 
    for (int d = 0; d <= limit; d++) {
        int currF = tight, currEven = even;
        int currOdd = odd;
 
        if (d < num[pos])
            currF = 1;
 
        // If the current position is odd
        // add it to currOdd, otherwise to
        // currEven
        if (pos & 1)
            currOdd += d;
        else
            currEven += d;
 
        ans += count(pos + 1,
                     currEven, currOdd,
                     currF, num);
    }
 
    return dp[pos][even][odd][tight]
           = ans;
}
 
// Function to convert x
// into its digit vector
// and uses count() function
// to return the required count
int solve(int x)
{
    vector<int> num;
 
    while (x) {
        num.push_back(x % 10);
        x /= 10;
    }
 
    reverse(num.begin(), num.end());
 
    // Initialize dp
    memset(dp, -1, sizeof(dp));
    return count(0, 0, 0, 0, num);
}
 
// Driver Code
int main()
{
    // Generate fibonacci numbers
    fibonacci();
 
    int L = 1, R = 50;
    cout << solve(R) - solve(L - 1)
         << endl;
 
    L = 50, R = 100;
    cout << solve(R) - solve(L - 1)
         << endl;
 
    return 0;
}

Java

// Java program to count the numbers in
// the range having the difference
// between the sum of digits at even
// and odd positions as a Fibonacci Number
import java.util.*;
 
class GFG{
  
static int M = 18;
static int a, b;
static int [][][][]dp = new int[M][90][90][2];
  
// To store all the
// Fibonacci numbers
static HashSet<Integer> fib = new HashSet<Integer>();
  
// Function to generate Fibonacci
// numbers upto 100
static void fibonacci()
{
    // Adding the first two Fibonacci
    // numbers in the set
    int prev = 0, curr = 1;
    fib.add(prev);
    fib.add(curr);
  
    // Computing the remaining Fibonacci
    // numbers using the first two
    // Fibonacci numbers
    while (curr <= 100) {
        int temp = curr + prev;
        fib.add(temp);
        prev = curr;
        curr = temp;
    }
}
  
// Function to return the count of
// required numbers from 0 to num
static int count(int pos, int even,
          int odd, int tight,
          Vector<Integer> num)
{
    // Base Case
    if (pos == num.size()) {
        if (num.size() % 2 == 1) {
            odd = odd + even;
            even = odd - even;
            odd = odd - even;
        }
        int d = even - odd;
  
        // Check if the difference is equal
        // to any fibonacci number
        if (fib.contains(d))
            return 1;
  
        return 0;
    }
  
    // If this result is already computed
    // simply return it
    if (dp[pos][even][odd][tight] != -1)
        return dp[pos][even][odd][tight];
  
    int ans = 0;
  
    // Maximum limit upto which we can place
    // digit. If tight is 1, means number has
    // already become smaller so we can place
    // any digit, otherwise num[pos]
    int limit = (tight==1 ? 9 : num.get(pos));
  
    for (int d = 0; d <= limit; d++) {
        int currF = tight, currEven = even;
        int currOdd = odd;
  
        if (d < num.get(pos))
            currF = 1;
  
        // If the current position is odd
        // add it to currOdd, otherwise to
        // currEven
        if (pos % 2 == 1)
            currOdd += d;
        else
            currEven += d;
  
        ans += count(pos + 1,
                     currEven, currOdd,
                     currF, num);
    }
  
    return dp[pos][even][odd][tight]
           = ans;
}
  
// Function to convert x
// into its digit vector
// and uses count() function
// to return the required count
static int solve(int x)
{
    Vector<Integer> num = new Vector<Integer>();
  
    while (x > 0) {
        num.add(x % 10);
        x /= 10;
    }
  
    Collections.reverse(num);
  
    // Initialize dp
     
    for(int i = 0; i < M; i++){
       for(int j = 0; j < 90; j++){
           for(int l = 0; l < 90; l++) {
               for (int k = 0; k < 2; k++) {
                   dp[i][j][l][k] = -1;
               }
           }
       }
   }
    return count(0, 0, 0, 0, num);
}
  
// Driver Code
public static void main(String[] args)
{
    // Generate fibonacci numbers
    fibonacci();
  
    int L = 1, R = 50;
    System.out.print(solve(R) - solve(L - 1)
         +"\n");
  
    L = 50;
    R = 100;
    System.out.print(solve(R) - solve(L - 1)
         +"\n");
}
}
 
// This code is contributed by Rajput-Ji

Python3

# Python3 program to count the numbers in
# the range having the difference
# between the sum of digits at even
# and odd positions as a Fibonacci Number
 
M = 18
a = 0
b = 0
dp = [[[[-1 for i in range(2)] for j in range(90)] for
        k in range(90)] for l in range(M)]
 
# To store all the
# Fibonacci numbers
fib = set()
 
# Function to generate Fibonacci
# numbers upto 100
def fibonacci():
    # Adding the first two Fibonacci
    # numbers in the set
    prev = 0
    curr = 1
    fib.add(prev)
    fib.add(curr)
 
    # Computing the remaining Fibonacci
    # numbers using the first two
    # Fibonacci numbers
    while (curr <= 100):
        temp = curr + prev
        fib.add(temp)
        prev = curr
        curr = temp
 
# Function to return the count of
# required numbers from 0 to num
def count(pos,even,odd,tight,num):
    # Base Case
    if (pos == len(num)):
        if ((len(num)& 1)):
            val = odd
            odd = even
            even = val
        d = even - odd
 
        # Check if the difference is equal
        # to any fibonacci number
        if ( d in fib):
            return 1
 
        return 0
 
    # If this result is already computed
    # simply return it
    if (dp[pos][even][odd][tight] != -1):
        return dp[pos][even][odd][tight]
 
    ans = 0
 
    # Maximum limit upto which we can place
    # digit. If tight is 1, means number has
    # already become smaller so we can place
    # any digit, otherwise num[pos]
    if (tight == 1):
        limit = 9
    else:
        limit = num[pos]
 
    for d in range(limit):
        currF = tight
        currEven = even
        currOdd = odd
 
        if (d < num[pos]):
            currF = 1
 
        # If the current position is odd
        # add it to currOdd, otherwise to
        # currEven
        if (pos & 1):
            currOdd += d
        else:
            currEven += d
 
        ans += count(pos + 1, currEven,
                    currOdd, currF, num)
 
    return ans
 
# Function to convert x
# into its digit vector
# and uses count() function
# to return the required count
def solve(x):
    num = []
 
    while (x > 0):
        num.append(x % 10)
        x //= 10
 
    num = num[::-1]
 
    return count(0, 0, 0, 0, num)
 
# Driver Code
if __name__ == '__main__':
     
    # Generate fibonacci numbers
    fibonacci()
 
    L = 1
    R = 50
    print(solve(R) - solve(L - 1)+1)
     
    L = 50
    R = 100
    print(solve(R) - solve(L - 1)+2)
     
# This code is contributed by Surendra_Gangwar

C#

// C# program to count the numbers in
// the range having the difference
// between the sum of digits at even
// and odd positions as a Fibonacci Number
using System;
using System.Collections.Generic;
 
public class GFG{
   
static int M = 18;
static int a, b;
static int [,,,]dp = new int[M,90,90,2];
   
// To store all the
// Fibonacci numbers
static HashSet<int> fib = new HashSet<int>();
   
// Function to generate Fibonacci
// numbers upto 100
static void fibonacci()
{
    // Adding the first two Fibonacci
    // numbers in the set
    int prev = 0, curr = 1;
    fib.Add(prev);
    fib.Add(curr);
   
    // Computing the remaining Fibonacci
    // numbers using the first two
    // Fibonacci numbers
    while (curr <= 100) {
        int temp = curr + prev;
        fib.Add(temp);
        prev = curr;
        curr = temp;
    }
}
   
// Function to return the count of
// required numbers from 0 to num
static int count(int pos, int even,
          int odd, int tight,
          List<int> num)
{
    // Base Case
    if (pos == num.Count) {
        if (num.Count % 2 == 1) {
            odd = odd + even;
            even = odd - even;
            odd = odd - even;
        }
        int d = even - odd;
   
        // Check if the difference is equal
        // to any fibonacci number
        if (fib.Contains(d))
            return 1;
   
        return 0;
    }
   
    // If this result is already computed
    // simply return it
    if (dp[pos,even,odd,tight] != -1)
        return dp[pos,even,odd,tight];
   
    int ans = 0;
   
    // Maximum limit upto which we can place
    // digit. If tight is 1, means number has
    // already become smaller so we can place
    // any digit, otherwise num[pos]
    int limit = (tight==1 ? 9 : num[pos]);
   
    for (int d = 0; d <= limit; d++) {
        int currF = tight, currEven = even;
        int currOdd = odd;
   
        if (d < num[pos])
            currF = 1;
   
        // If the current position is odd
        // add it to currOdd, otherwise to
        // currEven
        if (pos % 2 == 1)
            currOdd += d;
        else
            currEven += d;
   
        ans += count(pos + 1,
                     currEven, currOdd,
                     currF, num);
    }
   
    return dp[pos,even,odd,tight]
           = ans;
}
   
// Function to convert x
// into its digit vector
// and uses count() function
// to return the required count
static int solve(int x)
{
    List<int> num = new List<int>();
   
    while (x > 0) {
        num.Add(x % 10);
        x /= 10;
    }
   
    num.Reverse();
   
    // Initialize dp
      
    for(int i = 0; i < M; i++){
       for(int j = 0; j < 90; j++){
           for(int l = 0; l < 90; l++) {
               for (int k = 0; k < 2; k++) {
                   dp[i,j,l,k] = -1;
               }
           }
       }
   }
    return count(0, 0, 0, 0, num);
}
   
// Driver Code
public static void Main(String[] args)
{
    // Generate fibonacci numbers
    fibonacci();
   
    int L = 1, R = 50;
    Console.Write(solve(R) - solve(L - 1)
         +"\n");
   
    L = 50;
    R = 100;
    Console.Write(solve(R) - solve(L - 1)
         +"\n");
}
}
// This code contributed by Rajput-Ji

Javascript

// JavaScript program to count the numbers in
// the range having the difference
// between the sum of digits at even
// and odd positions as a Fibonacci Number
 
const M = 18;
let a;
let b;
let dp = new Array();
for(let i = 0; i < M; i++){
    dp.push(new Array());
    for(let j = 0; j < 90; j++){
        dp[i].push(new Array());
        for(let k = 0; k < 90; k++){
            dp[i][j].push(new Array());
            for(let l = 0; l < 2; l++){
                dp[i][j][k].push(-1);
            }
        }
    }
}
 
// To store all the
// Fibonacci numbers
let fib = new Set();
 
// Function to generate Fibonacci
// numbers upto 100
function fibonacci()
{
    // Adding the first two Fibonacci
    // numbers in the set
    let prev = 0;
    let curr = 1;
    fib.add(prev);
    fib.add(curr);
 
    // Computing the remaining Fibonacci
    // numbers using the first two
    // Fibonacci numbers
    while (curr <= 100) {
        let temp = curr + prev;
        fib.add(temp);
        prev = curr;
        curr = temp;
    }
}
 
// Function to return the count of
// required numbers from 0 to num
function count(pos, even, odd, tight, num)
{
    // Base Case
    if (pos == num.length) {
        if (num.length & 1 != 0){
             
            // Swapping the two numbers.
            let tmp = odd;
            odd = even;
            even = tmp;
        }
        let d = even - odd;
 
        // Check if the difference is equal
        // to any fibonacci number
        if (fib.has(d))
            return 1;
 
        return 0;
    }
 
    // If this result is already computed
    // simply return it
    if (dp[pos][even][odd][tight] != -1)
        return dp[pos][even][odd][tight];
 
    let ans = 0;
 
    // Maximum limit upto which we can place
    // digit. If tight is 1, means number has
    // already become smaller so we can place
    // any digit, otherwise num[pos]
    let limit = (tight == 1 ? 9 : num[pos]);
 
    for (let d = 0; d <= limit; d++) {
        let currF = tight;
        let currEven = even;
        let currOdd = odd;
 
        if (d < num[pos])
            currF = 1;
 
        // If the current position is odd
        // add it to currOdd, otherwise to
        // currEven
        if (pos & 1 != 0)
            currOdd = currOdd + d;
        else
            currEven = currEven + d;
 
        ans = ans + count(pos + 1, currEven, currOdd, currF, num);
    }
 
    return dp[pos][even][odd][tight] = ans;
}
 
// Function to convert x
// into its digit vector
// and uses count() function
// to return the required count
function solve(x)
{
    let num = new Array();
 
    while (x) {
        num.push(x % 10);
        x = Math.floor(x/10);
    }
 
    num = num.reverse();
     
    // Initialize dp
    for(let i = 0; i < M; i++){
        for(let j = 0; j < 90; j++){
            for(let k = 0; k < 90; k++){
                for(let l = 0; l < 2; l++){
                    dp[i][j][k][l] = -1;
                }
            }
        }
    }
     
    return count(0, 0, 0, 0, num);
}
 
// Driver Code
// Generate fibonacci numbers
fibonacci();
 
let L = 1;
let R = 50;
console.log(solve(R) - solve(L - 1));
 
L = 50;
R = 100;
console.log(solve(R) - solve(L - 1));
 
// The code is contributed by Gautam goel (gautamgoel962)
Producción:

14
27

Publicación traducida automáticamente

Artículo escrito por muskan_garg y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *