(SPOJ) f91 - Solution 2

Two years ago, I solved this problem using the language C (the only solution using C in this blog). You can check the previous solution here.

Although the solution could be as simple as:
  • If n <= 100, print 91
  • If n >= 101, print n-10
This solution calculates the answer through the given recursion, which is:
  • If n <= 100, do f91(n) = f91(f91(n+11)
  • If n >= 101, do f91(n) = n-10


import java.io.*;

class Main  {
    public static int f91(int n) {
        if (n >= 101) {
            return n-10;
        }
       
        return f91(f91(n+11));
    }
   
    public static int reader(BufferedReader br) throws NumberFormatException, IOException {     
        int n;
        int resp = 0;     
      
        while (true) {         
            n = br.read();         
            if (n >= '0' && n <= '9') {
                break;
            }  
        }
           
        while (true) {         
            resp = resp*10 + n-'0';         
            n = br.read();         
            if (n < '0' || n > '9') {
                break;     
            }
        }
      
        return resp;     
    }
   
    public static void process() throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
  
        int n = reader(br);
        while (n != 0) {
            int nn = f91(n);
           
            bw.write("f91(" + n + ") = " + nn + "\n");
            n = reader(br);
        }
       
        bw.flush();
        bw.close();
    }
   
    public static void main(String[] args) throws NumberFormatException, IOException {
        Main m = new Main();
        m.process();

        System.exit(0);
    }
}

Comments

Popular posts from this blog

(Coderbyte) Powers of Two - Solução

(Coderbyte) Dash Insert II - Solução

(CoderByte) Number Search - Solução