I tried optimizing code with buffer

using System;
using System.Collections.Generic;
using System.IO;using System.Linq;
class Solution {
    static void Main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution */
        int total=int.Parse(Console.ReadLine());
        for(int i=0;i<total;i++){
            string str=Console.ReadLine();
            int number=int.Parse(str.Split(‘ ‘)[0]);
            int m=int.Parse(str.Split(‘ ‘)[1]);
            Console.WriteLine(calculate(number)%m);
        }
    }
    static Dictionary<int,long> buffer=new Dictionary<int,long>();
    static long calculate(int number){
        return sigmat(number);
    }
    static int g(int n){
        int i=0;
        while(sf(i)!=n){
            i++;
        }
        return i;
    }
    static long sigmat(int n){
        long sum=0;
        int buff=buffercheck(n,ref sum)+1;
        for(int i=buff;i<=n;i++){
            int sgval=sg(i);
            sum+=sgval;
            buffer.Add(i,sum);
        }
        return sum;
    }
    static int buffercheck(int n,ref long sum){
        int max=0;
        for(int i=0;i<buffer.Count;i++){
            if(max<=buffer.ElementAt(i).Key && buffer.ElementAt(i).Key <=n ){
                max=buffer.ElementAt(i).Key;
                sum=buffer.ElementAt(i).Value;
                if(max==n) {
                    return n;
                }
            }
        }
        return max;
    }
    static int sg(int n){
        n=g(n);
        int sum=0;
         while(n>0){
            sum+=n%10;
            n=n/10;
        }
        return sum;
    }
    static int f(int n){
        int sum=0;
        while(n>0){
            int sumA=n%10;
            int factorial=1;
            while(sumA>1){
                factorial*=(sumA–);
            }
            sum+=factorial;
            n=n/10;
        }
        return sum;
    }
    static int sf(int n){
        n=f(n);
        int sum=0;
         while(n>0){
            sum+=n%10;
            n=n/10;
        }
        return sum;
    }
}

Leave a comment

Design a site like this with WordPress.com
Get started