Java Loops II

  • + 0 comments

    Java

    Solution using Map for memoization for better performance

    public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            sc.nextLine();
            while(sc.hasNextLine()){
                String[] linea = sc.nextLine().split(" ");
                int a = Integer.parseInt(linea[0]); 
                int b = Integer.parseInt(linea[1]);
                int n = Integer.parseInt(linea[2]);
                
                // Create a map in order to save previously calculated values
                Map<Integer, Double> map = new HashMap<>();
                StringBuilder sb = new StringBuilder();
                
                map.put(0, Math.pow(2, 0)*b);
                for(int i = 1; i < n; i++){
                    map.put(i, map.get(i-1) + Math.pow(2, i)*b);
                }
                map.values().forEach(v -> sb.append( a + Math.round(v) +" "));
                System.out.println(sb.substring(0, sb.length()-1))    ;
                
            }
            sc.close();
        }