lundi 6 décembre 2021

Can you please help here : Sums of Digit Factorials

Hello developers community

I would to solve this problem illustrated in this image using C++

Define f(n) as the sum of the factorials of the digits of n. For example, f(342) = 3! + 4! + 2! = 32.

Define sf(n) as the sum of the digits of f(n). So sf(342) = 3 + 2 = 5.

Define g(i) to be the smallest positive integer n such that sf(n) = i. Though sf(342) is 5, sf(25) is also 5, and it can be verified that g(5) is 25.

Define sg(i) as the sum of the digits of g(i). So sg(5) = 2 + 5 = 7.

Further, it can be verified that g(20) is 267 and ∑ sg(i) for 1 ≤ i ≤ 20 is 156.

What is ∑ sg(i) for 1 ≤ i ≤ 150?

enter image description here

Here is below my approch, could you please hep here? my code takes long time running, and it works

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

int factorial(int n);
std::vector<int> int_to_vector(int n);
int sum_vector(std::vector<int> v);
int get_smallest_number(std::vector<int> v, int sum, int n);
int sum_sg(int n )


int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    int q;
    int m,n;
    int g;
    int sum = 0;
    std::vector<int> vec;
    
    cin>>q;
    if( 1<=q && q<=100000){
        
    std::vector<int> s;
    int fact = 0;
    int sg = 0;
    for ( int i = 0; i < q; i++){
        
       cin>>n>>m;
       fact = factorial(n);
       s = int_to_vector(fact);
       sum = sum_vector(s);
       g = get_smallest_number(s, sum, n);
       s = int_to_vector(g);
       sum = sum_vector(s);
    
    }
    
    }
    
       
    return 0;
}

int factorial(int n){
 
 if (n==0) return 1;
 return factorial(n-1)*n;     
}

std::vector<int> int_to_vector(int n){
    
    std::vector<int> numbers;
     while(n>0)
    {
         numbers.push_back(n%10);
         n/=10;
    }
    return numbers;
}

int sum_vector(std::vector<int> v){
    
    int sum=0;
    
    for(int i = 0; i < v.size(); i++){
        
        sum+=v.at(i);
    }
    
    return sum;  
}

int get_smallest_number(std::vector<int> v, int sum, int n){
    
    int i = 0;
    int factoriel = 1;
    std::vector<int> vect;
    int sum2 = 0;
    
    
while( i < n){
    
    factoriel = factorial(i);
    vect = int_to_vector(factoriel);
    sum2 = sum_vector(vect);
    
    if( sum2 == sum) return i;
    
    i++ ;
}

return n;
    
}

Thanks in advance I think on recursive solutions, but it seems somhowe more complex to implement if there is any solutions using modern c++ and STL it will be wonderfull

Aucun commentaire:

Enregistrer un commentaire