#include<stdio.h>
int main(void){

  int i;
  char c[3];
  int ct=0;

  for(i=0;i<3;i++){
    scanf("%c",&c[i]);
  }

  for(i=0;i<3;i++){
    if(c[i]=='o')ct++;
  }

  printf("%d\n",700+100*ct);

  return 0;
}#include<stdio.h>
int main(void){

  int i;
  char c[3];
  int ct=0;

  for(i=0;i<3;i++){
    scanf("%c",&c[i]);
  }

  for(i=0;i<3;i++){
    if(c[i]=='o')ct++;
  }

  printf("%d\n",700+100*ct);

  return 0;
}#include<stdio.h>
int main(void){

  int i;
  char c[3];
  int ct=0;

  for(i=0;i<3;i++){
    scanf("%c",&c[i]);
  }

  for(i=0;i<3;i++){
    if(c[i]=='o')ct++;
  }

  printf("%d\n",700+100*ct);

  return 0;
}#include<stdio.h>
int main(void){

  int i;
  char c[3];
  int ct=0;

  for(i=0;i<3;i++){
    scanf("%c",&c[i]);
  }

  for(i=0;i<3;i++){
    if(c[i]=='o')ct++;
  }

  printf("%d\n",700+100*ct);

  return 0;
}


function Main(input) {
    var cnt = 0;
    for(var i = 0 ; i < 3 ; ++i) {
        if (input[i] === 'o') cnt += 100;
    }

    console.log(700 + cnt);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function main (s) {
var res=0;
for(var i=0;i<s.length;i++)if(s[i]=='o')res++;
console.log(700+res*100);
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));


'use strict';

function Main(INPUT) {
    const S = INPUT.split("");
    let y = 700;
    for (let i = 0; i < S.length; i++) {
        y += S[i] == "o" ? 100 : 0;
    }
    console.log(y);
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function main(input){
  const a = input.trim().split('');
  let ans = 700;
  a.forEach(function(a){
    if(a=='o'){
      ans+=100;
    }
  });
  console.log(700+ans);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function main(input){
  const a = input.trim().split('');
  let count = 0;
  a.forEach(function(a){
    if(a[i]=='o'){
      count+=100;
    }
  });
  //let cnt = parseInt(count, 10);
  console.log(700+count);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function main(input){
  const a = input.trim();
  let count = 0;
  for(let i=0; i<3; i++){
    if(a[i]=='o'){
      c+=100;
    }
  }
  console.log(700+c);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


package main

import (
    . "fmt"
    "strings"
)

func main() {
    var s string
    Scanf("%s", &s)

    ans := 700
    sa := strings.Split(s, "")
    for _, v := range sa {
        if v == "o" {
            ans += 100
        }
    }

    Println(ans)
 }


package main

import (
        "fmt"
)

func main() {
        var s string
        fmt.Scan(&s)
        ans := 700
        for _, s := range s {
                if string(s) == "o" {
                        ans += 100
                }
        }
        fmt.Println(ans)
}


package main

import (
	"fmt"
	"strings"
)

func main() {
	var a string
	fmt.Scan(&a)
	r := 700 + strings.Count(a, "o")*100
	fmt.Println(r)
}


package main

import "fmt"

func main() {
	var s string
	fmt.Scan(&s)

	ans := 700

	for _, v := range s {
		if v == '○' {
			ans += 100
		}
	}
	fmt.Println(ans)
}


package main

import (
	"bufio"
	"fmt"
	"log"
	"math"
	"os"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)

func main() {
	sc.Split(bufio.ScanWords)
	log.SetFlags(log.Lshortfile)
	s:=nextString()
        for i:=0; i<3; i++ {
ans :=700
    if s[i] =='o'{
ans+=100
}
    }
fmt.Println(ans)
}

func nextString() string {
	sc.Scan()
	return sc.Text()
}

func nextInt() int {
	sc.Scan()
	i, err := strconv.Atoi(sc.Text())
	if err != nil {
		panic(err)
	}
	return i
}

var dy = []int{0, 1, 0, -1}
var dx = []int{1, 0, -1, 0}
var MAX = math.MaxInt32

func pow(a, b int) int {
	return int(math.Pow(float64(a), float64(b)))
}

func lcm(a, b int) int {
	return a * b / gcd(a, b)
}
func gcd(a, b int) int {
	if a < b {
		a, b = b, a
	}
	for b != 0 {
		a, b = b, a%b
	}
	return a
}
func max(a ...int) int {
	r := a[0]
	for i := 0; i < len(a); i++ {
		if r < a[i] {
			r = a[i]
		}
	}
	return r
}
func min(a ...int) int {
	r := a[0]
	for i := 0; i < len(a); i++ {
		if r > a[i] {
			r = a[i]
		}
	}
	return r
}
func sum(a []int) (r int) {
	for i := range a {
		r += a[i]
	}
	return r
}
func abs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

type Pair struct {
	a, b int
}

type Pairs []Pair

func (p Pairs) Len() int {
	return len(p)
}
func (p Pairs) Swap(i, j int) {
	p[i], p[j] = p[j], p[i]
}

func (p Pairs) Less(i, j int) bool {
	if p[i].a == p[j].a {
		return p[i].b < p[j].b
	}
	return p[i].a < p[j].a
}


package main

import (
	"bufio"
	"fmt"
	"log"
	"math"
	"os"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)

func main() {
	sc.Split(bufio.ScanWords)
	log.SetFlags(log.Lshortfile)
	s:=nextString()
        for i:=1; i<4; i++ {
ans :=700
    if s[i] =='o'{
and+=100
}
    }
fmt.Println(ans)
}

func nextString() string {
	sc.Scan()
	return sc.Text()
}

func nextInt() int {
	sc.Scan()
	i, err := strconv.Atoi(sc.Text())
	if err != nil {
		panic(err)
	}
	return i
}

var dy = []int{0, 1, 0, -1}
var dx = []int{1, 0, -1, 0}
var MAX = math.MaxInt32

func pow(a, b int) int {
	return int(math.Pow(float64(a), float64(b)))
}

func lcm(a, b int) int {
	return a * b / gcd(a, b)
}
func gcd(a, b int) int {
	if a < b {
		a, b = b, a
	}
	for b != 0 {
		a, b = b, a%b
	}
	return a
}
func max(a ...int) int {
	r := a[0]
	for i := 0; i < len(a); i++ {
		if r < a[i] {
			r = a[i]
		}
	}
	return r
}
func min(a ...int) int {
	r := a[0]
	for i := 0; i < len(a); i++ {
		if r > a[i] {
			r = a[i]
		}
	}
	return r
}
func sum(a []int) (r int) {
	for i := range a {
		r += a[i]
	}
	return r
}
func abs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

type Pair struct {
	a, b int
}

type Pairs []Pair

func (p Pairs) Len() int {
	return len(p)
}
func (p Pairs) Swap(i, j int) {
	p[i], p[j] = p[j], p[i]
}

func (p Pairs) Less(i, j int) bool {
	if p[i].a == p[j].a {
		return p[i].b < p[j].b
	}
	return p[i].a < p[j].a
}


a=gets.chomp.split("").map { |e|
if e == "o"
  e = 1.to_i
else
  e = 0.to_i
end   }.inject(:+)

puts 700+100*a


options = gets.chomp.split("").map(&:to_s)
i = 0
options.each do |o|
  if o == "o"
    i += 1
  end
end
puts (700 + 100*i)


S = gets.chomp
ans = 700
for i in 0..2
    if S[i] == 'o'
        ans += 100
    end
end
puts ans


s1,s2,s3 = gets.chomp.split("").map(&:to_i);
"o" == 100
"x" == 0

s = s1 + s2 + s3
puts s + 700


s1,s2,s3 = gets.chomp.split("").map(&:to_i);
"o" == 100
"x" == 0

puts s1 + s2 + s3 + 700


S = gets.chomp
p S
pos = S.count('o')
p pos
if pos == 1
  p "800円"
elsif pos == 2
  p "900円"
elsif pos == 3
  p "1000円"
else
  p "700円"
end


#[allow(dead_code)]
fn is_whitespace(c: &char) -> bool {
    c.is_whitespace()
}

#[allow(dead_code)]
fn is_eol(c: &char) -> bool {
    ['\r', '\n'].contains(c)
}

#[allow(unused_macros)]
macro_rules! input {
    ($var:ident, $($r:tt)*) => {
        input_inner!{$var, $($r)*}
    };

    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        #[allow(unused_mut, unused_variables, bare_trait_objects)]
        let mut next = move |f: &Fn(&char)->bool| -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|f(&c))
                .take_while(|c|!f(&c))
                .collect()
        };
        input_inner!{next, $($r)*};
    };
}

#[allow(unused_macros)]
macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};

    ($next:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };

    ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => {
        let mut $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };
}

#[allow(unused_macros)]
macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };

    ($next:expr, [ $t:tt ; eol ]) => {
        $next(&is_eol).split(' ').map(|x| x.parse::<$t>().unwrap()).collect::<Vec<_>>()
    };

    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };

    ($next:expr, chars) => {
        read_value!($next, String).chars().collect::<Vec<char>>()
    };

    ($next:expr, bytes) => {
        read_value!($next, String).into_bytes()
    };

    ($next:expr, usize1) => {
        read_value!($next, usize) - 1
    };

    ($next:expr, parser) => {
        $next
    };

    ($next:expr, $t:ty) => {
        $next(&is_whitespace).parse::<$t>().expect("Parse error")
    };
}

#[allow(unused_imports)]
use std::cmp::{max, min};
#[allow(unused_imports)]
use std::collections::{BinaryHeap, HashMap, HashSet};

#[allow(dead_code)]
struct Edge {
    from: usize,
    to: usize,
}

#[allow(dead_code)]
type Graph = Vec<Vec<usize>>;
#[allow(dead_code)]
const M: usize = 1_000_000_007;

fn main() {
    input! {
        s: chars,
    }

    println!(
        "{}",
        700 + s.into_iter().filter(|&x| x == 'o').count() * 100
    );
}


use std::io;

fn main() {
	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let s:Vec<char> = buf.trim().chars().collect();
	let mut ramen = 700;
	for i in 0..3 {
		if s[i] == 'o' {
			ramen += 100;
		}
	}
	println!("{}", ramen);
}


use std::io::*;
use std::str::FromStr;

pub fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("failed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}

fn main() {
    let s: Vec<char> = read::<String>().chars().collect();
    println!("{}", 700 + 100 * s.iter().filter(|&x| *x == 'o').count())
}


use std::cmp::*;

#[allow(unused_macros)]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

#[allow(unused_macros)]
macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};

    ($next:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };
}

#[allow(unused_macros)]
macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };

    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };

    ($next:expr, chars) => {
        read_value!($next, String).chars().collect::<Vec<char>>()
    };

    ($next:expr, usize1) => {
        read_value!($next, usize) - 1
    };

    ($next:expr, $t:ty) => {
        $next().parse::<$t>().expect("Parse error")
    };
}

#[allow(unused_macros)]
macro_rules! debug {
    ($($a:expr),*) => {
        eprintln!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
    }
}

#[allow(unused_macros)]
macro_rules! max {
    ($x:expr) => {
      $x
    };
    ($x:expr, $($xs:tt)+) => {
      max($x,max!($($xs)+))
    };
  }

#[allow(unused_macros)]
macro_rules! min {
    ($x:expr) => {
      $x
    };
    ($x:expr, $($xs:tt)+) => {
      min($x,min!($($xs)+))
    };
  }

use std::ascii::AsciiExt;
use std::collections::HashMap;
use std::collections::VecDeque;
use std::io::Write;
use std::iter::Iterator;

#[derive(PartialEq, Debug, Clone)]
pub struct UnionFindNode {
    pub par: usize,
    pub rank: usize,
}

#[derive(PartialEq, Debug, Clone)]
pub struct UnionFind(pub Vec<UnionFindNode>);

impl UnionFind {
    //初期化
    pub fn new(size: usize) -> UnionFind {
        let mut vec = Vec::new();
        for i in 0..size {
            vec.push(UnionFindNode { par: i, rank: 0 });
        }

        UnionFind(vec)
    }

    //根を求める
    pub fn find(&mut self, x: usize) -> usize {
        if self.0[x].par == x {
            x
        } else {
            let par = self.0[x].par;
            let v = self.find(par);
            self.0[x].par = v;
            v
        }
    }

    //xとyの集合を併合
    pub fn unite(&mut self, x: usize, y: usize) {
        let x = self.find(x);
        let y = self.find(y);
        if x == y {
            return;
        }

        if self.0[x].rank < self.0[y].rank {
            self.0[x].par = y;
        } else {
            self.0[y].par = x;
            if self.0[x].rank == self.0[y].rank {
                self.0[x].rank += 1;
            }
        }
    }

    //xとyが同じ集合に属するか
    pub fn same(&mut self, x: usize, y: usize) -> bool {
        self.find(x) == self.find(y)
    }
}

fn main() {
    input! {
        a:i64,
        b:i64,
        c:i64,
        x:i64,
        y:i64,
    }

    let mut total = 0;
    let mut sum = 0;
    for i in 1..x + 1 {
        sum = 2 * c * i;

        if x - i > 0 {
            sum = sum + (x - i) * a;
        }

        if y - i > 0 {
            sum = sum + (y - i) * b;
        }

        if total == 0 {
            total = sum;
        } else {
            total = min!(total, sum);
        }
    }

    if a + b < 2 * c {
        total = a * x + b * y;
    }

    println!("{}", total);
}


use std::str::FromStr;
use std::fmt::Debug;
use std::cmp;
#[allow(dead_code)]
fn read_as_vec<T>() -> Vec<T>
where T: FromStr, <T as FromStr>::Err : Debug{
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    s.trim().split_whitespace().map(|c| T::from_str(c).unwrap()).collect()

}

#[allow(dead_code)]
fn read_as_string() -> String{
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    s.trim().to_string()
}

fn main(){
    let s = read_as_string().chars().collect::<Vec<char>>();

    println!("{}", s.into_iter().filter(|x| *x == 'o').count() + 700);
}


use std::io::*;
use std::str::FromStr;
use std::char;

fn main() {
    let a: String = read::<char>();

}

fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("failed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}


//var i=700;readLine()!.characters.forEach{String($0)=="o" ?i+=100:i+=0};print(i)
var i=700
readLine()!.characters.forEach {
  	if String($0) == "o" {
      	i+=100
    } else {
      	i+=0
    }
}
print(i)


var i=700;readLine()!.characters.forEach{String($0)=="o" ?(i+=100):(i+=0)};print(i)


var i=700;readLine()!.characters.forEach{String($0)=="o" ?i+=100 :i+=0};print(i)


var i=700;readLine()!.characters.forEach{String($0)=="o" ?i+=100:i+=0};print(i)


const input=require('fs').readFileSync('/dev/stdin', 'utf8').split(/[\s]/);const nin=()=>{const r = input[0];input.shift();return Number(r)};const nrin=(n)=>{const a:number[]=[];rep(n,()=>a.push(nin()));return a};const sin=()=>{const r = input[0];input.shift();return String(r)};const out=(...a)=>{console.log(...a)};const floor=(a)=>{return Math.floor(a)};const abs=(a)=>{return Math.abs(a)};const min=(...a)=>{return Math.min(...a)};const max=(...a)=>{return Math.max(...a)};const rep=(n, callback)=>{for(let i = 0;i < n; i++){callback()}};const strrep=(s, i, v)=>{return s.slice(0, i)+v+s.slice(i+1);};const permutation=({result=[],pre=[],post,n=post.length})=>{if(n>0){post.forEach((_,i)=>{const rest=[...post];const elem=rest.splice(i, 1);permutation({result, pre: [...pre,...elem],post:rest,n:n-1})})}else{result.push(pre)}return result};const sw=(s,a:any[],op:'=='|'>='|'>'|'<='|'<'='==')=>{for(let i=0;i<a.length;i+=2){if(op==='=='){if(s==a[i])return a[i+1]}else if(op==='>='){if(s>=a[i])return a[i+1]}else if(op==='<='){if(s<=a[i])return a[i+1]}else if(op==='>'){if(s>a[i])return a[i+1]}else if(op==='<'){if(s<a[i])return a[i+1]}}return a[a.length-1];};const or=(a,...b)=>{for(let i=0;i<b.length;i++)if(a==b[i])return true;return false};const maxindex=(...a)=>{return a.indexOf(Math.max.apply(null,a))};const asc=(ar:number[])=>{return ar.sort((a,b)=>{return a-b})};const desc=(ar:number[])=>{return ar.sort((a,b)=>{return b-a})};const ceil=a=>{return Math.ceil(a)};const srin=s=>{const a:string[]=[];rep(s,()=>a.push(sin()));return a};let ssinteger=-1;const ssin=()=>{ssinteger++;return input[0][ssinteger]};
const main = ()=>{
  let a=[ssin(),ssin(),ssin()]
  let ans=700;
  if(a[0]=='o') ans+=100
  if(a[1]=='o') ans+=100
  if(a[2]=='o') ans+=100
  out(ans)
}
main()


const stdin = require('fs').readFileSync('/dev/stdin', 'utf8')

const s = stdin.split('\n')[0].split('')

let len = 0

len += s.filter(e=>e==='o').length

console.log(len * 100 + 700)


const log = console.log;

// ----

function Main(input: string): void {
  const toppingCount = (input.match(/o/g) || []).length;

  log(700 + 100 * toppingCount);
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));


const main = (input) => {
  console.log(input.split('x').length -1 + 700);
}
main (require('fs').readFileSync('/dev/stdin', 'utf8'));


var lines: string[] = [];
var reader: any = require("readline").createInterface({
  input: process.stdin,
  output: process.stdout
});
reader.on("line", function(line: string) {
  lines.push(line);
});
reader.on("close", function() {
  var s = lines[0];
  console.log(s);
});


N = int(input().rstrip())
N_2=pow(N,2)
print(N*(1+N+N_2))


def main():
    N = int(input())
    print(N + N * N + N * N * N)

if __name__ == '__main__':
    main()

# import sys
# input = sys.stdin.readline
#
# sys.setrecursionlimit(10 ** 7)
#
# (int(x)-1 for x in input().split())
# rstrip()
#
# def binary_search(*, ok, ng, func):
#     while abs(ok - ng) > 1:
#         mid = (ok + ng) // 2
#         if func(mid):
#             ok = mid
#         else:
#             ng = mid
#     return ok


#!/usr/bin/env python3

a = int(input())

print(a+a**2+a**3)


a = int(input())
a = int(a ** 3)
print(a)


a = int(input())
)
a = int(a ** 3)
print(a)


a = int(input("Enter an integer : "))
s=a**2
t=a**3
print(a+s+t)


import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        InputReader in = new InputReader(System.in);
        PrintWriter w = new PrintWriter(System.out);
        int a = in.nextInt();
        w.println(a + (a * a) + (a * a * a));
        w.close();
    }

    static class InputReader {

        private final InputStream stream;
        private final byte[] buf = new byte[8192];
        private int curChar, snumChars;
        private SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int snext() {
            if (snumChars == -1)
                throw new InputMismatchException();
            if (curChar >= snumChars) {
                curChar = 0;
                try {
                    snumChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (snumChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = snext();
            while (isSpaceChar(c)) {
                c = snext();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = snext();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = snext();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public long nextLong() {
            int c = snext();
            while (isSpaceChar(c)) {
                c = snext();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = snext();
            }
            long res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = snext();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public int[] nextIntArray(int n) {
            int a[] = new int[n];
            for (int i = 0; i < n; i++) {
                a[i] = this.nextInt();
            }
            return a;
        }

        public long[] nextLongArray(int n) {
            long a[] = new long[n];
            for (int i = 0; i < n; i++) {
                a[i] = this.nextLong();
            }
            return a;
        }

        public String readString() {
            int c = snext();
            while (isSpaceChar(c)) {
                c = snext();
            }
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = snext();
            } while (!isSpaceChar(c));
            return res.toString();
        }

        public String nextLine() {
            int c = snext();
            while (isSpaceChar(c))
                c = snext();
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = snext();
            } while (!isEndOfLine(c));
            return res.toString();
        }

        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        private boolean isEndOfLine(int c) {
            return c == '\n' || c == '\r' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);
        }
    }
}


import java.io.*;
import java.util.*;
public class Main {

public static void main(String[] args) {
    InputReader sc = new InputReader(System.in);
    PrintWriter pw = new PrintWriter(System.out);
    Random gen = new Random();
    int test = 1;//sc.nextInt();
    while(test-->0) {

        int n = sc.nextInt();
        long ans = n + n*n + n*n*n;
        pw.println(ans);

    }
    pw.close();

}

static class InputReader {

    private final InputStream stream;
    private final byte[] buf = new byte[8192];
    private int curChar, snumChars;

    public InputReader(InputStream st) {
        this.stream = st;
    }

    public int read() {
        if (snumChars == -1)
            throw new InputMismatchException();
        if (curChar >= snumChars) {
            curChar = 0;
            try {
                snumChars = stream.read(buf);
            } catch (IOException e) {
                throw new InputMismatchException();
            }
            if (snumChars <= 0)
                return -1;
        }
        return buf[curChar++];
    }

    public int nextInt() {
        int c = read();
        while (isSpaceChar(c)) {
            c = read();
        }
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        int res = 0;
        do {
            res *= 10;
            res += c - '0';
            c = read();
        } while (!isSpaceChar(c));
        return res * sgn;
    }

    public long nextLong() {
        int c = read();
        while (isSpaceChar(c)) {
            c = read();
        }
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        long res = 0;
        do {
            res *= 10;
            res += c - '0';
            c = read();
        } while (!isSpaceChar(c));
        return res * sgn;
    }

    public int[] nextIntArray(int n) {
        int [] a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = nextInt();
        }
        return a;
    }

    public static int[] shuffle(int[] a, Random gen)
    { for(int i = 0, n = a.length;i < n;i++)
    { int ind = gen.nextInt(n-i)+i;
        int d = a[i];
        a[i] = a[ind];
        a[ind] = d;

    }
        return a;
    }

    public String readString() {
        int c = read();
        while (isSpaceChar(c)) {
            c = read();
        }
        StringBuilder res = new StringBuilder();
        do {
            res.appendCodePoint(c);
            c = read();
        } while (!isSpaceChar(c));
        return res.toString();
    }

    public String nextLine() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        StringBuilder res = new StringBuilder();
        do {
            res.appendCodePoint(c);
            c = read();
        } while (!isEndOfLine(c));
        return res.toString();
    }

    public boolean isSpaceChar(int c) {
        return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

    private boolean isEndOfLine(int c) {
        return c == '\n' || c == '\r' || c == -1;
    }

}

}


import java.util.*;
import java.io.*;

public class Main {
	static FastReader in = new FastReader();

	public static void main(String[] args) {
		solve();
	}

	static void solve() {
		int n = in.nextInt();
		System.out.println(n + n * n + n * n * n);
	}

	static class FastReader {
		BufferedReader br;
		StringTokenizer st;

		public FastReader() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}

		String next() {
			while (st == null || !st.hasMoreElements()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return st.nextToken();
		}

		int nextInt() {
			return Integer.parseInt(next());
		}

		long nextLong() {
			return Long.parseLong(next());
		}

		double nextDouble() {
			return Double.parseDouble(next());
		}

		String nextLine() {
			String str = "";
			try {
				str = br.readLine();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return str;
		}

		int[] readarr(int abc) {
			int[] a = new int[abc];
			for (int i = 0; i < abc; i++)
				a[i] = nextInt();
			return a;
		}
	}
}


import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        // Your code here!

        Scanner scan = new Scanner(System.in);

        int x = scan.nextInt();

        System.out.println(x + x*x + Math.pow(x,3));
    }
}


import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        // Your code here!

        Scanner scan = new Scanner(System.in);

        int x = scan.nextInt();

        System.out.printlf(x + x*x + Math.pow(x,3));
    }
}


import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        Scanner scan = new Scanner(System.in);
        int a = scan.nextInt();
        System.out.println(a + Math.pow(a, 2) + Math.pow(a, 3));
    }
}


#include <bits/stdc++.h>
using namespace std;
using lint = long long;
using P = pair<int, int>;
using vec = vector<int>;
using mat = vector<vector<int>>;
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define all(v) v.begin(), v.end()
#define endl "\n"

constexpr int MOD = 1000000007;
const int INF = 1 << 30;

int main() {
    int a;
    cin >> a;
    cout << a + a * a + a * a * a << endl;
    return 0;
}


#include <bits/stdc++.h>
#include <climits>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstring>
#include <chrono>
#include <complex>
#define ll long long int
#define si(x) scanf("%d", &x)
#define sl(x) scanf("%lld", &x)
#define ss(s) scanf("%s", s)
#define pi(x) printf("%d\n", x)
#define pl(x) printf("%lld\n", x)
#define ps(s) printf("%s\n", s)
#define deb(x) cout << #x << "=" << x << endl
#define deb2(x, y) cout << #x << "=" << x << "," << #y << "=" << y << endl
#define loop(i, L, R) for (int i = L; i < R; ++i)
#define looprev(i, L, R) for (int i = L; i > R; --i)
#define MAX(x, y) (x > y ? x : y)
#define MIN(x, y) (x < y ? x : y)
#define wh(t) while (t--)
#define pii pair<int, int>
#define ppi pair<int, pii>
#define pll pair<ll, ll>
#define ppl pair<ll, pll>
#define vii vector<int>
#define vvi vector<vii>
#define vl vector<ll>
#define vvl vector<vl>
#define maxHi priority_queue<int>
#define maxHl priority_queue<ll>
#define minHi priority_queue < int, vector<int>, greater<int>>
#define minHl priority_queue < ll, vector<ll>, greater<ll>>
#define mod 1000000007
#define inf 1000000000000000001
#define PI 3.1415926535897932384626
#define all(x) x.begin(), x.end()
#define sortall(x) sort(all(x))
#define mp(x, y) make_pair(x, y)
#define mem(a, val) memset(a, val, sizeof(a))
#define eb emplace_back
#define pb push_back
#define F first
#define S second
#define IOS ios_base::sync_with_stdio(false)
#define endl "\n"
using namespace std;

/*  AH SH*T,  HERE WE GO AGAIN.  */

void solve()
{
    ll i, j, n, m;

    sl(n);

    ll ans = n + n * n + n * n * n;

    cout << ans << endl;

}

int32_t main()
{

    IOS;
    cin.tie(NULL);

#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif

    int T = 1;

    wh(T)
    {

        solve();

    }
}


#include <iostream>
using namespace std;

int a;

int main() {
    /*Jovando Haryo K
    X2*/
    cin >> a;
    cout << a+a*a+a*a*a << endl;
}


#include<bits/stdc++.h>
using namespace std;

#define ll long long
#define pll pair<ll,ll>

vector<ll> S(10000006, 0);
vector<ll> A(10000006, 0);

int main(){

	ios_base::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);

	ll n;
	cin>>n;

	ll ans=0;
	for(ll i=1;i<=n;i++){
		ll k=n/i;
		ans+=i*k*(k+1)>>1;
	}
	cout<<ans<<endl;
}


#include <iostream>
using namespace std;

int main() {
  int n;
  cin >> n;
  cout << a + a*a + a*a*a;
}


# include <iostream>
using namespace std;

static const int ans[] = {
      3,  14,  39,  84,  155,
    258, 399, 584, 819, 1110,
};

int main() {
    int a;
    cin >> a;
    cout << ans[a] << endl;
    return 0;
}


#include<stdio.h>
long long n, m, i, j, k, s, ans, x, y;
int main()
{
	scanf ("%lld", &n);
	printf ("%lld", n + n * n + n * n * n);
	return 0;
}


#include <stdio.h>
int main(void){
	int a;
	scanf("%d", &a);
	printf("%d\n", a+a*a+a*a*a);
	return 0;
}


#include<stdio.h>

int main(void){
    long n;
    scanf("%ld",&n);
    printf("%ld",n + n*n + n*n*n);
}


# include <iostream>
using namespace std;

static const int ans[] = {
    0, 3, 14, 39, 84, 155, 258, 399, 584, 819, 1110
};

int main() {
    int a;
    scanf("%d", &a);
    printf("%d", ans[a]);
    return 0;
}


#include <stdio.h>

 int a;

int main(){
    scanf(%d, &a);
    printf(%d, a+a*a+a*a*a);
    return 0;
}


#include<stdio.h>

int main()
{
    int a;
     scanf("%d",a);
    printf("%d\n",a+a*a+a*a*a);
    return 0;
}


function main(input){
  const hoge = Number(input);
  console.log(hoge + Math.pow(hoge, 2) + Math.pow(hoge, 3));
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function main(arg) {
    let a = Number(arg)
    console.log(Math.pow(a,1) + Math.pow(a,2) + Math.pow(a,3))
}

main(require("fs").readFileSync("/dev/stdin", "utf8"));


'use strict'

function main(input) {
    const a = Number(input.split('\n')[0].split(' ')[0]);
    console.log(a + a*a + a*a*a);
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function Main(input) {
  const box = input;
  let one = box;
  let two = box**2;
  let three = box**3;

  console.log(one + two + three);

}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(input) {
  const box = input;

  let one = box;
  let two = box**2;
  let three = box**3;

  console.log(one + two + three);

}
Main(input);


function Main(input) {
	const box = input;
    let one = box;
    let two = box**2;
    let three = box**3;

    console.log(one + two + three);
}
let input = 10;
Main(input);


package main

import (
    "fmt"
)

func main(){
    var a int
    fmt.Scan(&a)

    fmt.Println(a*(1+a*(1+a)))
}


package main

import (
	"fmt"
	"math"
)

func main() {

	var a float64
	fmt.Scan(&a)

	ans := a + math.Pow(a, 2) + math.Pow(a, 3)

	fmt.Println(int(ans))

}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

func main() {
	a := getStdinInt()
	fmt.Printf("%d\n", a+a*a+a*a*a)
}

var sc = bufio.NewReaderSize(os.Stdin, 1024*1024*1)

func getStdin() string {
	return readLine()
}
func getStdinInt() int {
	str := getStdin()
	rtn, _ := strconv.Atoi(str)
	return rtn
}
func readLine() string {
	buf := make([]byte, 0, 0)
	for {
		l, p, _ := sc.ReadLine()
		buf = append(buf, l...)
		if !p {
			break
		}
	}
	return string(buf)
}


import "fmt"

func main() {
	var a int

	fmt.Scan(&a)

	fmt.Println(a * (1 + a*(1+a)))
}


package main

import (
  "fmt"
  "math"
)

func main() {
  var n int
  fmt.Scan(&n)
  ans := n + int(math.Pow(float64(n), 2) + math.Pow(float64(n), 3))


package main

import (
  "fmt"
  "math"
)

func main() {
  var n int
  fmt.Scan(&n)
  ans = n + math.Pow(n, 2) + math.Pow(n, 3)
  fmt.Println(ans)
}


a = gets.chomp.to_i

puts a + a**2 + a**3


a = gets.to_i
ans = a + (a*a) + (a*a*a)

puts ans


a = gets.to_i
p a+a*a+a*a*a


a=gets.to_i
p a+a+a*a+a*a*a


va = gets.chomp.to_i

puts a + a**2 + a**3


a = gets
puts a + a*a + a*a*a


use proconio::input;

fn main() {
    input! {
        a: usize,
    };
    println!("{}", a + a * a + a * a * a);
}


fn main(){
    let raw = input();
    let a = raw.parse::<i64>().unwrap();
    println!("{}", a + (a*a) + (a*a*a));
}

fn input() -> String{
    let mut buf = String::new();
    std::io::stdin().read_line(&mut buf).unwrap();
    buf.trim_end().to_string()
}


#![allow(unused_imports)]
#![allow(non_snake_case)]
use std::cmp::*;
use std::collections::*;
use std::io::Write;

#[allow(unused_macros)]
macro_rules! debug {
    ($($e:expr),*) => {
        #[cfg(debug_assertions)]
        $({
            let (e, mut err) = (stringify!($e), std::io::stderr());
            writeln!(err, "{} = {:?}", e, $e).unwrap()
        })*
    };
}

fn main() {
    let n = read::<usize>();
    let ans = n + n * n + n * n * n;
    println!("{}", ans);
}

fn read<T: std::str::FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().parse().ok().unwrap()
}

fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    read::<String>()
        .split_whitespace()
        .map(|e| e.parse().ok().unwrap())
        .collect()
}


fn read<T: std::str::FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().parse().ok().unwrap()
}

fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    read::<String>()
        .split_whitespace()
        .map(|e| e.parse().ok().unwrap())
        .collect()
}

fn main() {
    let v = read_vec::<u32>();
    let num = v[0];
    let result = calc(num);
    println!("{}", result)
}


// これバイナリ提出せずにそのまま通るの?
// https://qiita.com/tanakh/items/60f42e06edcffd8d99a7
use competitive::prelude::*;

fn main() {
    input! {
        a: i64,
    }

    let ans = a + a.pow(2) + a.pow(3);
    echo!(ans);
}


let a = Int(readLine()!)!

print(a + a * a + a * a * a)


let a = Int(readLine()!)!
print(a + a*a + a*a*a)


let a = Int(readLine()!)!
print(a*a*a + a*a + a)


import Foundation

let input_line: String = readLine()!
let split: [String] = input_line.components(separatedBy: " ")

let a = Int(split[0])!

print(a+a^2+a^3)


//=Main Part==================================================================//
@inlinable
func main(_ args: [String]) -> Int32 {
  // Your code goes here
  let a = geti()
  print(a * (a * (a + 1) + 1))

  return 0
}

//=Utilities for Programming Contests=========================================//
import Foundation
import os
// input
@discardableResult
@inlinable @inline(__always) func gets() -> String { readLine()! }
@inlinable @inline(__always) func geti() -> Int    { Int(gets())! }
@inlinable @inline(__always) func getd() -> Double { Double(gets())! }
// array
@inlinable @inline(__always) func getsA(_ c: Character = " ") -> [String] { gets().split(separator: c).map(String.init) }
@inlinable @inline(__always) func getiA(_ c: Character = " ") -> [Int]    { gets().split(separator: c).map{ Int(String.init($0))! } }
@inlinable @inline(__always) func getdA(_ c: Character = " ") -> [Double] { gets().split(separator: c).map{ Double(String.init($0))! } }
// structured bindings: splat
prefix operator *
@inlinable @inline(__always) prefix func * <E> (a: [E]) -> (E, E)       { (a[0], a[1]) }
@inlinable @inline(__always) prefix func * <E> (a: [E]) -> (E, E, E)    { (a[0], a[1], a[2]) }
@inlinable @inline(__always) prefix func * <E> (a: [E]) -> (E, E, E, E) { (a[0], a[1], a[2], a[3]) }

//=Execution==================================================================//
os.exit(main(CommandLine.arguments))


let a = Int(readLine()!)!
print(a + Int(truncating: pow(Decimal(a), 2) as NSDecimalNumber) + Int(truncating: pow(Decimal(a), 3) as NSDecimalNumber))


import { readFileSync } from 'fs'

function main(input: string) {
  const a = Number(input)

  const result = a + a ** 2 + a ** 3

  console.log(result)
}

main(readFileSync('/dev/stdin', 'utf8').trim())


import * as fs from 'fs';

// main
function main(input: string[]) {
    // param
    var a: number;
    var ans: number;
    // init
    a = Number(input[0]);
    // solve
    ans = a + a*a+ a*a*a;
    // answer
    console.log(ans);
}

// graph lib
/*
function GRAPH_enumPattern(cur: number[], pat: number[][]): number[][] {
    var arr = [];
    for (var patx = 0; patx < pat.length; patx++) {
        var pos = [cur[0] + pat[patx][0], cur[1] + pat[patx][1]];
        arr.push(pos);
    }
    return arr;
}
*/

// math lib
/*
function Math_max(arr: number[]): number { return arr.reduce((x, y) => Math.max(x, y)); }
function Math_min(arr: number[]): number { return arr.reduce((x, y) => Math.min(x, y)); }
function Math_gcd(): number {
    var ans = arguments[0];
    var f = (a: number, b: number): number => b ? f(b, a % b) : a
    for (var i = 1; i < arguments.length; i++) {
        ans = f(ans, arguments[i]);
    }
    return ans
};
function Math_gcdArray(values: number[]): number {
    var ans = values[0];
    var f = (a: number, b: number): number => b ? f(b, a % b) : a
    for (var i = 1; i < values.length; i++) {
        ans = f(ans, values[i]);
    }
    return ans
};
function Math_lcm(): number {
    var a = arguments
    var g = (n: number, m: number): number => m ? g(m, n % m) : n
    var l = (n: number, m: number): number => n * m / g(n, m)
    var ans = a[0]
    for (var i = 1; i < a.length; i++) {
        ans = l(ans, a[i])
    }
    return ans
}
function Math_lcmArray(values: number[]): number {
    var a = values
    var g = (n: number, m: number): number => m ? g(m, n % m) : n
    var l = (n: number, m: number): number => n * m / g(n, m)
    var ans = a[0]
    for (var i = 1; i < a.length; i++) {
        ans = l(ans, a[i])
    }
    return ans
}
function Math_primeList(value: number): number[] {
    var ans = [];
    var arr = new Array(value).fill(0);
    for (var i = 2; i < value; i++) {
        if (arr[i] == 0) {
            for (var j = i; j < value; j += i) {
                if (arr[j] == 0) arr[j] = i;
            }
        }
    }
    for (var i = 2; i < value; i++) {
        if (arr[i] == i) ans.push(i);
    }
    return ans;
}
function Math_primeFactor(p: number[], value: number): number[][] {
    var ans: number[][] = [];
    var valmax = value / 2;;
    for (var i = 0; i < p.length; i++) {
        var prime = p[i];
        if (valmax < prime) break;
        var count = 0;
        while (value % prime == 0) {
            value /= prime;
            count++;
        }
        if (count != 0) {
            ans.push([prime, count]);
        }
        if (value == 1) break;
    }
    return ans;
}
*/

// union-find lib
/*
var g_uf_root: number[];
var g_uf_count: number[];
function UF_initRoot(num: number) {
    g_uf_root = new Array(num).fill(-1);
    g_uf_count = new Array(num).fill(1);
}
function UF_getRoot(index: number) {
    if (g_uf_root[index] < 0) {
        return index;
    } else {
        var work0: number = UF_getRoot(g_uf_root[index]);
        g_uf_root[index] = work0;
        return work0
    }
}
function UF_mergeRoot(a: number, b: number) {
    var root0: number = UF_getRoot(a);
    var root1: number = UF_getRoot(b);
    if (root0 == root1) return;
    if (root0 > root1) [root0, root1] = [root1, root0];
    g_uf_count[root0] += g_uf_count[root1];
    g_uf_count[root1] = 0;
    g_uf_root[root1] = root0;
}
*/

// entrypoint
function entrypoint() {
    try {
        // linux
        var input = fs.readFileSync("/dev/stdin", "utf8").trim().split("\n");
        console.debug = function () { };
        main(input);
    }
    catch (ex) {
        // windows
        const lines: string[] = [];
        // @ts-ignore
        const reader = require('readline').createInterface({
            // @ts-ignore
            input: process.stdin,
            // @ts-ignore
            output: process.stdout
        });
        reader.on('line', function (line: string) {
            lines.push(line);
        });
        reader.on('close', function () {
            input = lines;
            main(input);
        });
    }
}
entrypoint();


import * as fs from 'fs';

const a: number = +fs.readFileSync('/dev/stdin', 'utf8').trim();
const ans: number = a + Math.pow(a, 2) + Math.pow(a, 3);
console.log(ans);


import { readFileSync } from 'fs'
import { reverse } from 'dns'
import { start } from 'repl'

let lines: string[] = [];
const reader = require('readline').createInterface({
    input: process.stdin,
    output: process.stdout
});

reader.on('line', function (line: string) {
    lines.push(line);
});
reader.on('close', function () {
    /* let [n, d] = lines[0].split(' ').map( _ => parseInt(_)) */
    let n = parseInt(lines[0])

    console.log(n + n^2 + n^3)
});


"use strict";
const Main = (input) =>{
   let xs = input.trim().split('\n');
   let N = parseInt(xs[0].split(' ')[0]);
   let M = parseInt(xs[0].split(' ')[1]);
   let K = parseInt(xs[0].split(' ')[2]);
   let A = xs[1].split(' ').map(v=>parseInt(v,10));
   let B = xs[2].split(' ').map(v=>parseInt(v,10));
   let x = 0;
   let y = 0;
   let ans = 0;
   for(let i=0; i<N; i++){
      let tmp =0;
        x = A[i];
        y = B[i];
        if(x>y){
          tmp += y;
          //console.log(tmp);
        }else if(x<y){
          tmp += x;
          //console.log(tmp);
        }
      if(tmp<=K){
        ans++
      }else{
        break;
      }
   }
   console.log(ans);
}
Main(require('fs').readFileSync('/dev/stdin','utf8'));


R = int(input())

if R < 1200:
  print("ABC")
elif R < 2800:
  print("ARC")
else:
  print("AGC")


R = int(input())
print('ABC' if R < 1200 else ('ARC' if R < 2800 else 'AGC'))


a = int(input())

if a < 1200:
	print("ABC")
elif a >= 1200 and a < 2800:
	print("ARC")
else:
	print("AGC")


r = int(input())

if r < 1200:
  print('ABC')
elif r < 2800:
  print('ARC')
else:
  print('AGc')


def main():
	D,G = map(int,input().split())
	ListPC = [list(map(int,input().split())) for d in range(D)]
	ans = sum([i[0] for i in ListPC])

	for i in range(2**D):
		TempPoint,num,restmax = 0,0,-1  # 点数,正解数,解いてない最高点数idx
		for j in range(D):  # 全埋め問題加算
			if i>>j & 1:
				TempPoint += 100*(j+1)*ListPC[j][0]+ListPC[j][1]
				num += ListPC[j][0]
			else:
				restmax = max(j,restmax)
		if TempPoint >= G: # 合格なら更新
			ans = min(num,ans)
		elif G - TempPoint // ((restmax + 1) * 100) <= ListPC[restmax][0]: # 最高問題解いて合格なら更新
			ans = min(num + (G - TempPoint - 1) // ((restmax + 1) * 100) + 1, ans)
	print(ans)

if __name__ == '__main__':
	main()


n = int(input())

if n < 1200:
    print('ABC')
if n >= 1200 and n < 2800:
    print('ARC')
else:
    print('AGC')


import java.io.*;
import java.util.*;

public class Main {
    public static void main(String arg[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int R = Integer.parseInt(br.readLine());
        if(R<1200){
            System.out.println("ABC");
        }else if(R<2800){
            System.out.println("ARC");
        }else{
            System.out.println("AGC");
        }
    }
}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class Main {
  public static void main(String[] args) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    int r = Integer.parseInt(in.readLine());
    if(r<1200)
      System.out.println("ABC");
    else if(r<2800)
      System.out.println("ARC");
    else
      System.out.println("AGC");
  }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

	public static void main(String[] args) throws IOException{

		InputStreamReader inputStreamReader = new InputStreamReader(System.in);
		BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

		String input = bufferedReader.readLine();
		int r = Integer.parseInt(input);

		String result = "AGC";

		if(r < 1200) {
			result = "ABC";
		}else if(r < 2800) {
			result = "ARC";
		}

		print(result);
	}

	public static void print(String string) {
		System.out.println(string);
	}

}


import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		// TODO 自動生成されたメソッド・スタブ
		Scanner stdIn = new Scanner(System.in);

		int R = stdIn.nextInt();

		if(R < 1400) {
			System.out.println("ABC");
		}
		else if(R < 2800)
		{
			System.out.println("ARC");
		}
		else
		{
			System.out.println("AGC");
		}

	}

}


import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        int R = sc.nextInt();
        if(R < 1200){
            System.out.println("ABC");
        }else if(1200 < R && R < 2800){
            System.out.println("ARC");
        }else if(2800 < R){
            System.out.println("AGC");
        }
    }
}


public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        Main m = new Main(sc);
        m.show(m.solve());
        sc.close();
    }

	//フィールド
    Scanner sc;
    int R;

    //入力
    Main(Scanner sc) {
        this.sc = sc;
        this.R = sc.nextInt();
    }

    //解答処理
    private String solve() {
        String answer = "ABC";

        if (1200 <= R && R < 2800) {
        	answer = "ARC";
        } else if (2800 <= R) {
        	answer = "AGC";
        }

        return answer;
    }

    //出力
    public void show(String answer) {
        System.out.println(answer);
    }

}


#include<cctype>
#include<cstdio>
#include<cstring>

int getint(){
	int x=0,f=0;char ch=getchar();
	while(!isdigit(ch)) f|=ch=='-',ch=getchar();
	while(isdigit(ch)) x=(x<<1)+(x<<3)+(ch^48),ch=getchar();
	return f?-x:x;
}

signed main(){
	int n=getint();
	if(n<1200) printf("ABC");
	else if(n<2800) printf("ARC");
	else printf("AGC");
	return 0;
}


#include<stdio.h>
int main()
{
    int n;
    scanf("%d",&n);
    if(n<1200)
        printf("ABC\n");
    else if(n<2800)
        printf("ARC\n");
    else printf("AGC\n");
    return 0;
}


#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
#define NIL -2000000001
#define MAX 2000000000000

int main() {
  int n;
  scanf("%d", &n);
  if (n < 1200) {
    printf("ABC\n");
  } else if (n < 2800) {
    printf("ARC\n");
  } else {
    printf("AGC\n");
  }

  return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define mod 1000000007
int mulMod(long long a, long long b) {
    a *= b;
    a %= mod;
    return (int)a;
}
int addMod(int a, int b) {
    long long c = a + b;
    if(c >= mod) {
        c -= mod;
    }
    return (int)c;
}
vector<int> readArray(int n){
    vector<int> arr(n);
    for(int i=0; i<n; i++) {
        cin>>arr[i];
    }
    return arr;
}
void printArray(vector<int> &arr) {
    for(int a: arr)
        cout<<a<<" ";
    cout<<endl;
}

int main() {

    string x;
    cin>>x;
  	int n = x.length();
    long long c=0,bc=0,abc=0;
    int multi=1;
    reverse(x.begin(),x.end());
    for(int i=0;i<n;i++) {
        if(x[i]=='A') {
            abc=(abc+bc)%mod;
        }
        if(x[i]=='B') {
            bc=(bc+c)%mod;
        }
        if(x[i]=='C') {
            c=(c+multi)%mod;
        }
        if(x[i]=='?') {
            abc=(abc*3LL)%mod;
            abc=(abc+bc)%mod;
            bc=(bc*3LL)%mod;
            bc=(bc+c)%mod;
            c=(c*3LL)%mod;
            c=(c+multi)%mod;
            multi=(multi*3LL)%mod;
        }
    }
    cout<<(abc%mod)<<endl;
}


#include <iostream>
#include <map>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <sstream>
#include <cmath>
#include <math.h>
#include <string>
using namespace std;
typedef long long ll;
#define rep(n) for( int i = 0 ; i < n ; i++ )
#define REP(n) for( int i = 1 ; i <= n ; i++ )
#define repll(n) for( ll i = 0 ; i < n ; i++ )
#define REPll(n) for( ll i = 1 ; i <= n ; i++ )
#define rep2(n) for( int j = 0 ; j < n ; j++ )
#define REP2(n) for( int j = 1 ; j <= n ; j++ )
#define repll2(n) for( ll j = 0 ; j < n ; j++ )
#define REPll2(n) for( ll j = 1 ; j <= n ; j++ )

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n;
    if( n < 1200 ) cout << "ABC";
    else if( n < 2800 ) cout << "ARC";
    else cout << "AGC";
}


#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
int main() {
  string S;
  cin>>S;
  int a=S.size();
  bool ans=true;
  if(S[0]!='A'){
      ans=false;
  }
  int cnt=0;
    for(int i=2; i<a-1; i++){
        if(S[i]=='C'||S[i]=='c'){
            cnt++;
        }
    }
  	if(S[S.size()-1]=='C'||S[S.size()-1]=='c'){
		ans=false;

    }
    if(cnt!=1){
        ans=false;
    }
  if(ans==true){
      cout<<"AC"<<endl;
  }
  else{
      cout<<"WA"<<endl;
  }
}


#include<stdio.h>
int main()
{
	int n;
	scanf("%d",&n);
	if(n<1200){
		printf("ABC\n");
	}
	else if(n<2800){
		printf("ARC\n");
	}
	else printf("AGC\n");
}


#include<stdio.h>
int main()
{
	int r;
	scanf("%d",&r);
	if(r<1200)
	    printf("ABC\n");
	else if(r<2800)
	    printf("ARC\n");
	else
	    printf("AGC\n");
	return 0;
}


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main(){
  int R;
  scanf("%d",&R);
  if(R < 1200) printf("ABC\n");
  else if(1200 <= R & R < 2800) printf("ARC\n");
  else printf("AGC");
}


#include <stdio.h>
#include <string.h>

int main() {
	char S[9];
	scanf("%s",S);
	if (S[0] == 'A') {
		if(S[2] == 'C' || S[strlen(S)-3] == 'C') {
			printf("AC");
		} else {
			printf("WA");
		}
	} else {
		printf("WA");
	}
}


#include <stdio.h>
#include <string.h>

int main() {
	char S[9];
	scanf("%s",S);
	if (S[0] == 'A') {
		if(S[2] == 'C' || S[strlen(S)-2] == 'C') {
			printf("AC");
		} else {
			printf("WA");
		}
	} else {
		printf("WA");
	}
}


#include <stdio.h>

int main(void)
{
        int R;
        scanf("%d",&R);
        if(R<1200)printf("ABC\n");
        else if(R>=1200 && R>2800)printf("ARC\n");
        else if(R>=2800)printf("AGC\n");
        return 0;
}


function Main(input) {
  input = input.trim()
  if(input>=2800){
  console.log("AGC")
  }else if(input>=1200){
  console.log("ARC")
  }else{
  console.log("ABC")
  }
}Main(require("fs").readFileSync("/dev/stdin", "utf8"));


"use strict"
// inputに入力データ全体が入る
function Main(input){
    input = parseInt(input);
    if(input < 1200){
        console.log("ABC");
    }else if(input < 2800){
        console.log("ARC");
    }else{
        console.log("AGC");
    }
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(input) {
	input = parseInt(input.trim());
  if(input < 1200){
     console.log("ABC");
  }else if(input >= 1200 && input <2800){
    console.log("ARC");
  }else{
    console.log("AGC");
  }
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function main(input) {
  const ratz = /[a-z]/
  const S = input.split('');
  let ans = 'WA';
  let cCnt = 0;
  let lowCnt = 0;

  for (let i = 0; i < S.length; i++) {
    // 小文字カウント
    if (ratz.test(S[i])) {
      lowCnt++;
    }

    // C文字判定
    if (2 <= i && i < S.length - 1) {
      if(S[i] === 'C') { cCnt++; }
    }
  }

  if (S[0] === 'A'
      && cCnt === 1
      && lowCnt === (S.length - 2)) {
    ans = 'AC';
  }

  console.log(ans);
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));


const main = function(input){
  var rate = parseInt(input);

  if(rate<1200){
  	console.log("ABC");
  }else if(rate<2800){
  	console.log("ARC");
  }else{
  	console.log("AGC");
  }

}

main(require("fs").readFileSync("/dev/stdin","utf-8");


function Main(input) {
  input = input.trim()
  if(input>2800){
  console.log("AGC")
  }else if(input>1200){
  console.log("ARC")
  }else{
  console.log("ABC")
  }
}Main(require("fs").readFileSync("/dev/stdin", "utf8"));


package main

import (
	"bufio"
	"container/heap"
	"fmt"
	"math"
	"os"
	"strconv"
)

const (
	initialBufSize = 10000
	maxBufSize     = 1000000
	mod            = 1e9 + 7
)

var (
	sc *bufio.Scanner = func() *bufio.Scanner {
		sc := bufio.NewScanner(os.Stdin)
		buf := make([]byte, initialBufSize)
		sc.Buffer(buf, maxBufSize)
		sc.Split(bufio.ScanWords)
		return sc
	}()
)

func main() {
	R := getInt()

	if R < 1200 {
		fmt.Println("ABC")
	} else if R < 2800 {
		fmt.Println("ARC")
	} else {
		fmt.Println("AGC")
	}
}

type Graph struct {
	n     int
	edges [][]int
}

func NewGraph(n int) *Graph {
	g := &Graph{
		n:     n,
		edges: make([][]int, n),
	}
	return g
}

func (g *Graph) AddEdge(u, v int) {
	g.edges[v] = append(g.edges[v], u)
	g.edges[u] = append(g.edges[u], v)
}

func dfs(c int, edges [][]int, visited map[int]struct{}) {
	visited[c] = struct{}{}

	for _, v := range edges[c] {
		_, flag := visited[v]
		if flag {
			continue
		}
		dfs(v, edges, visited)
	}
}

func bfs(c int, graph *Graph) {
	next := make([]int, 0)
	next = append(next, c)
	visited := make(map[int]struct{})

	for ; len(next) != 0; {
		u := next[0]
		next = next[1:]
		visited[u] = struct{}{}

		for _, v := range graph.edges[u] {
			_, flag := visited[v]
			if flag {
				continue
			}

			// なにか処理

			next = append(next, v)
		}
	}
}

func getInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func getIntArray(n int) []int {
	array := make([]int, n)
	for i := 0; i < n; i++ {
		array[i] = getInt()
	}
	return array
}

func getString() string {
	sc.Scan()
	return sc.Text()
}

func abs(a int) int {
	return int(math.Abs(float64(a)))
}

func pow(p, q int) int {
	return int(math.Pow(float64(p), float64(q)))
}

func powMod(n, p int) int {
	if p == 0 {
		return 1
	} else if p%2 == 0 {
		t := powMod(n, p/2)
		return calcMod(t * t)
	} else {
		return calcMod(n * powMod(n, p-1))
	}
}

func min(nums ...int) int {
	if len(nums) == 0 {
		panic("funciton min() requires at least one argument.")
	}
	res := nums[0]
	for i := 0; i < len(nums); i++ {
		res = int(math.Min(float64(res), float64(nums[i])))
	}
	return res
}

func max(nums ...int) int {
	if len(nums) == 0 {
		panic("funciton max() requires at least one argument.")
	}
	res := nums[0]
	for i := 0; i < len(nums); i++ {
		res = int(math.Max(float64(res), float64(nums[i])))
	}
	return res
}

func strSearch(a []string, b string) bool {
	for i := 0; i < len(a); i++ {
		if a[i] == b {
			return true
		}
	}
	return false
}

func printIntArray(array []int) {
	strArray := fmt.Sprint(array)
	fmt.Println(strArray[1 : len(strArray)-1])
}

func calcMod(x int) int {
	return x % mod
}

func reverse(s string) string {
	runes := []rune(s)
	for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
		runes[i], runes[j] = runes[j], runes[i]
	}
	return string(runes)
}

func isPrime(n int) bool {
	if n < 2 {
		return false
	} else if n == 2 {
		return true
	} else if n % 2 == 0 {
		return false
	}

	sqrtN := int(math.Sqrt(float64(n)))
	for i := 3; i <= sqrtN; i += 2 {
		if n % i == 0 {
			return false
		}
	}

	return true
}

func contains(s []int, e int) bool {
	for _, v := range s {
		if e == v {
			return true
		}
	}
	return false
}

func makeRange(min, max int) []int {
	a := make([]int, max-min+1)
	for i := range a {
		a[i] = min + i
	}
	return a
}

func powerset2(nums []int) [][]int {
	length := int(math.Pow(2, float64(len(nums))))
	result := make([][]int, length)

	index := 0
	result[index] = []int{}
	index++

	for _, n := range nums {
		max := index
		for i := 0; i < max; i++ {
			result[index] = copyAndAppend(result[i], n)
			index++
		}
	}

	return result
}

func copyAndAppend(nums []int, n int) []int {
	dst := make([]int, len(nums)+1)
	copy(dst, nums)
	dst[len(nums)] = n
	return dst
}

func calcGcd(x, y int) int {
	if y == 0 {
		return x
	} else if x >= y {
		return calcGcd(y, x % y)
	} else {
		return calcGcd(x, y % x)
	}
}

func getDivisor(n int) []int {
	var divisor []int
	divisor = append(divisor, 1)
	if n != 1 {
		divisor = append(divisor, n)
	}

	sqrt := int(math.Sqrt(float64(n)))
	for i := 2; i <= sqrt; i++ {
		if n % i == 0 {
			divisor = append(divisor, i)
			divisor = append(divisor, n/i)
		}
	}
	return divisor
}

type intHeap []int

func (h intHeap) Len() int {
	return len(h)
}

func (h intHeap) Less(i, j int) bool {
	return h[i] > h[j]
}

func (h intHeap) Swap(i, j int) {
	h[i], h[j] = h[j], h[i]
}

func (h *intHeap) Push(x interface{}) {
	*h = append(*h, x.(int))
}

func (h *intHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

func initHeap() *intHeap {
	ih := &intHeap{}
	heap.Init(ih)
	return ih
}

func (h *intHeap) pushHeap(n int) {
	heap.Push(h, n)
}

func (h *intHeap) popHeap() int {
	return heap.Pop(h).(int)
}

func factMod(n int) int {
	value := 1
	for ; n > 1; n-- {
		value = calcMod(value * n)
	}
	return value
}

func combinationMod(n, k int) int {
	factN := factMod(n)
	factK := factMod(k)
	factNK := factMod(n - k)
	factKR := powMod(factK, mod - 2)
	factNKR := powMod(factNK, mod - 2)
	return calcMod(factN * calcMod(factKR * factNKR))
}


package main

import (
	"bufio"
	"fmt"
	"log"
	"math"
	"os"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)

func main() {
	sc.Split(bufio.ScanWords)
	log.SetFlags(log.Lshortfile)
	r := nextInt()
	c := ""
	if r < 1200 {
		c = "ABC"
	} else if r < 2800 {
		c = "ARC"
	} else {
		c = "AGC"
	}
	fmt.Println(c)
}

func nextString() string {
	sc.Scan()
	return sc.Text()
}

func nextInt() int {
	sc.Scan()
	i, err := strconv.Atoi(sc.Text())
	if err != nil {
		panic(err)
	}
	return i
}

var dy = []int{0, 1, 0, -1}
var dx = []int{1, 0, -1, 0}
var MAX = math.MaxInt32

func pow(a, b int) int {
	return int(math.Pow(float64(a), float64(b)))
}

func lcm(a, b int) int {
	return a * b / gcd(a, b)
}
func gcd(a, b int) int {
	if a < b {
		a, b = b, a
	}
	for b != 0 {
		a, b = b, a%b
	}
	return a
}
func max(a ...int) int {
	r := a[0]
	for i := 0; i < len(a); i++ {
		if r < a[i] {
			r = a[i]
		}
	}
	return r
}
func min(a ...int) int {
	r := a[0]
	for i := 0; i < len(a); i++ {
		if r > a[i] {
			r = a[i]
		}
	}
	return r
}
func sum(a []int) (r int) {
	for i := range a {
		r += a[i]
	}
	return r
}
func abs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

type Pair struct {
	a, b int
}

type Pairs []Pair

func (p Pairs) Len() int {
	return len(p)
}
func (p Pairs) Swap(i, j int) {
	p[i], p[j] = p[j], p[i]
}

func (p Pairs) Less(i, j int) bool {
	if p[i].a == p[j].a {
		return p[i].b < p[j].b
	}
	return p[i].a < p[j].a
}


package main

import "fmt"

func main() {
	var r int
	fmt.Scan(&r)
	if r < 1200 {
		fmt.Println("ABC")
	} else if r < 2800 {
		fmt.Println("ARC")
	} else {
		fmt.Println("AGC")
	}
}


package main

import "fmt"

func main() {
	var r int
	fmt.Scan(&r)
	if r < 1200 {
		fmt.Println("ABC")
	} else if r < 2808 {
		fmt.Println("ARC")
	} else {
		fmt.Println("AGC")
	}
}


//  ABC104_C_AllGreen.go
//

package main

import (
    "fmt"
    //"strings"
)

var pc [][]int
var pointMatrix [][]int
var rpointMatrix [][]int
var min int

func calPoint(point int,i int ,D int ,G int,correct int,min *int) {

  if i == D - 1 {
      for j := 0; j < len(rpointMatrix[i]); j++{
          //fmt.Println(j,":",point+pointMatrix[i][j],"correct:",correct+j)
          if point+rpointMatrix[i][j] >= G {
            if correct+j <= *min{
              *min = correct+j
           }
          }
      }
      return

  } else {

     for j := 0 ; j < len(rpointMatrix[i]) ; j++ {
       //fmt.Print(j,"-")
        if correct+j >= *min {
           break
        }

        if point+rpointMatrix[i][j] >= G  {
          if correct +j <= *min {
            *min = correct + j
          }
          break
        }
        calPoint(point+rpointMatrix[i][j],i+1,D,G,correct+j,min)
     }
  }
}

func main() {
  var D int
  var G int
  var P int
  var C int
  var point int
  var correct int

  fmt.Scan(&D,&G)

  pc = make([][]int,D)

  for i := 0; i < D; i++ {
     pc[i] = make([]int,2)
  }

  min = 1

  for i := 0 ; i < D ; i++ {
    fmt.Scan(&P,&C)
    pc[i][0] = P
    pc[i][1] = C
    min *= P

    }

  //fmt.Println(pc)

  pointMatrix = make([][]int,D)

  for i := 0; i < D; i++ {
    pointMatrix[i] = make([]int,pc[i][0]+1)
  }

  for i :=0; i < D; i++ {
    for j :=0 ; j <= pc[i][0]; j++ {
      pointMatrix[i][j] = j * (i+1) * 100
    }
      pointMatrix[i][pc[i][0]] += pc[i][1]
   }

  rpointMatrix = make([][]int,D)

  for i := 0; i < D; i++ {
    rpointMatrix[i] = make([] int,pc[D-1-i][0]+1)
    rpointMatrix[i] = pointMatrix[D-1-i]
  }

  //fmt.Println(pointMatrix)
  //fmt.Println(rpointMatrix)

  point = 0
  correct = 0

  calPoint(point,0,D,G,correct,&min)

  //fmt.Println(point,correct,min)
  fmt.Println(min)
}


//  ABC104_C_AllGreen.go
//

package main

import (
    "fmt"
    //"strings"
)

var pc [][]int
var pointMatrix [][]int
var min int

func calPoint(point int,i int ,D int ,G int,correct int,min *int) {

  if i == D - 1 {
      for j := 0; j < pc[i][0]+1; j++{
          //fmt.Println(j,":",point+pointMatrix[i][j],"correct:",correct+j)
          if point+pointMatrix[i][j] >= G && correct+j <= *min {
             *min = correct+j
          }
      }
      return

  } else {

     for j := 0 ; j < pc[i][0]+1 ; j++ {
       //fmt.Print(j,"-")
        if correct+j >= *min {
           return
        }
        calPoint(point+pointMatrix[i][j],i+1,D,G,correct+j,min)
     }
  }
}

func main() {
  var D int
  var G int
  var P int
  var C int
  var point int
  var correct int

  fmt.Scan(&D,&G)

  pc = make([][]int,D)

  for i := 0; i < D; i++ {
     pc[i] = make([]int,2)
  }

  min = 1

  for i := 0 ; i < D ; i++ {
    fmt.Scan(&P,&C)
    pc[i][0] = P
    pc[i][1] = C
    min *= P

    }

  //fmt.Println(pc)

  pointMatrix = make([][]int,D)

  for i := 0; i < D; i++ {
    pointMatrix[i] = make([]int,pc[i][0]+1)
  }

  for i :=0; i < D; i++ {
    for j :=0 ; j <= pc[i][0]; j++ {
      pointMatrix[i][j] = j * (i+1) * 100
    }
      pointMatrix[i][pc[i][0]] += pc[i][1]
   }

    //fmt.Println(pointMatrix)

  point = 0
  correct = 0

  calPoint(point,0,D,G,correct,&min)

  fmt.Println(min)
}


n = gets.to_i
if n < 1200
  puts :ABC
elsif n < 2800
  puts :ARC
else
  puts :AGC
end


#入力
r = gets.to_i

# こたえ
if r < 1200
  puts "ABC"
elsif r >= 1200 && r < 2800
  puts "ARC"
else
  puts "AGC"
end


r = gets.to_i
if r < 1200 then
	puts 'ABC'
else
	if r < 2800 then
		puts 'ARC'
	else
		puts 'AGC'
	end
end


puts gets.to_i<1200?"ABC":$_<2800?"ARC":"AGC"


r = gets.to_i
if r < 1200
  puts "ABC"
elsfi 1200 <= r && r < 2800
  puts "ARC"
else
  puts "AGC"
end


r = gets.to_i
if r <= 1200
  puts 'ABC'
elsif r <= 2800
  puts 'ARC'
else
  puts 'AGC'
end


#[allow(unused_macros, dead_code)]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

#[allow(unused_macros, dead_code)]
macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};

    ($next:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };

    ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => {
        let mut $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };
}

#[allow(unused_macros, dead_code)]
macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };

    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };

    ($next:expr, chars) => {
        read_value!($next, String).chars().collect::<Vec<char>>()
    };

    ($next:expr, bytes) => {
        read_value!($next, String).into_bytes()
    };

    ($next:expr, usize1) => {
        read_value!($next, usize) - 1
    };

    ($next:expr, $t:ty) => {
        $next().parse::<$t>().expect("Parse error")
    };
}

#[allow(dead_code)]
struct UnionFind {
    parent: Vec<usize>,
    rank: Vec<usize>,
    size: Vec<usize>,
}

#[allow(dead_code)]
impl UnionFind {
    fn new(n: usize) -> UnionFind {
        let mut p = vec![0; n];
        for i in 0..n {
            p[i] = i;
        }
        return UnionFind {
            parent: p,
            rank: vec![0; n],
            size: vec![1; n],
        };
    }

    fn find(&mut self, x: usize) -> usize {
        if x == self.parent[x] {
            x
        } else {
            let p = self.parent[x];
            let pr = self.find(p);
            self.parent[x] = pr;
            pr
        }
    }

    fn same(&mut self, a: usize, b: usize) -> bool {
        self.find(a) == self.find(b)
    }

    fn unite(&mut self, a: usize, b: usize) {
        let a_root = self.find(a);
        let b_root = self.find(b);
        if a_root == b_root {
            return;
        }
        if self.rank[a_root] > self.rank[b_root] {
            self.parent[b_root] = a_root;
            self.size[a_root] += self.size[b_root];
        } else {
            self.parent[a_root] = b_root;
            self.size[b_root] += self.size[a_root];
            if self.rank[a_root] == self.rank[b_root] {
                self.rank[b_root] += 1;
            }
        }
    }

    fn get_size(&mut self, x: usize) -> usize {
        let root = self.find(x);
        self.size[root]
    }
}

const MOD_P: usize = 1000000007;

#[allow(dead_code)]
// fact(n) = n! mod p
fn fact(n: usize) -> usize {
    let mut acc = 1;
    for i in 1..n + 1 {
        acc = acc * i % MOD_P;
    }
    acc
}

#[allow(dead_code)]
fn mod_pow(b: usize, mut e: usize) -> usize {
    let mut base = b;
    let mut acc = 1;

    while e > 1 {
        if e % 2 == 1 {
            acc = acc * base % MOD_P;
        }
        e /= 2;
        base = base * base % MOD_P;
    }

    if e == 1 {
        acc = acc * base % MOD_P;
    }

    acc
}

#[allow(dead_code)]
fn comb(n: usize, r: usize) -> usize {
    // nCr = n! / (r! (n-r)!) = n! (r!)^(p-2) ((n-r)!)^(p-2)
    let x = ((n - r + 1)..(n + 1)).fold(1, |p, x| p * x % MOD_P);
    let y = mod_pow(fact(r), MOD_P - 2);
    x * y % MOD_P
}

#[allow(dead_code)]
fn gcd(a: usize, b: usize) -> usize {
    if b > a {
        gcd(b, a)
    } else if a % b == 0 {
        b
    } else {
        gcd(b, a % b)
    }
}

#[allow(dead_code)]
fn getline() -> String {
    let mut __ret = String::new();
    std::io::stdin().read_line(&mut __ret).ok();
    return __ret;
}

use std::cmp::{max, min};

fn main() {
    input! {
        r: usize,
    }
    let ans = if r < 1200 {
        "ABC"
    } else if r < 2800 {
        "ARC"
    } else {
        "AGC"
    };
    println!("{}", ans);
}


use std::io::*;
use std::str::FromStr;

pub fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("failed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}

fn main() {
    let r: usize = read();
    let mut ans = "AGC";

    if r < 2800 {
        ans = "ARC";
    }

    if r < 1200 {
        ans = "ABC";
    }

    println!("{}", ans);
}


#[allow(unused_macros)]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

#[allow(unused_macros)]
macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};

    ($next:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };
}

#[allow(unused_macros)]
macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };

    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };

    ($next:expr, chars) => {
        read_value!($next, String).chars().collect::<Vec<char>>()
    };

    ($next:expr, usize1) => {
        read_value!($next, usize) - 1
    };

    ($next:expr, $t:ty) => {
        $next().parse::<$t>().expect("Parse error")
    };
}

#[allow(unused_macros)]
macro_rules! debug {
    ($($a:expr),*) => {
        eprintln!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
    }
}

use std::iter::Iterator;

fn main() {

    input!{
       R:usize,
    }

    let mut S = "";

    if R < 1200 {
        S = "ABC"
    }else if  1200 <= R && R < 2800 {
        S = "ARC"
    }else{
        S = "AGC"
    }

    println!("{}", S);

}


def main():
    r = (int)(input())
    if r < 1200:
        print("ABC")
    elif r >= 1200 and r < 2800:
        print("ARC")
    else:
        print("ARC")

main()


#[allow(unused_macros)]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};

    ($next:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };
}

macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };

    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };

    ($next:expr, chars) => {
        read_value!($next, String).chars().collect::<Vec<char>>()
    };

    ($next:expr, usize1) => {
        read_value!($next, usize) - 1
    };

    ($next:expr, $t:ty) => {
        $next().parse::<$t>().expect("Parse error")
    };
}

fn func(i: usize, g: i32, v: &std::vec::Vec<(i32, i32)>) -> Option<i32> {
    if i == 0 {
        // println!("g = {}", g);
        return if g <= 0 { Some(0) } else { None };
    }
    let (p, c) = v[i - 1];
    let mut res = std::vec::Vec::with_capacity((p + 1) as usize);
    for j in 0..(p + 1) {
        // print!("i = {}, j = {}, ", i, j);
        if j == 0 {
            res.push((j, func(i - 1, g, v)));
        } else if 1 <= j && j < p {
            res.push((j, func(i - 1, g - 100 * (i as i32) * j, v)));
        } else {
            res.push((j, func(i - 1, g - 100 * (i as i32) * j - c, v)));
        }
    }
    let r = res.into_iter().flat_map(|(j, r)| r.map(|x| x + j)).min();
    // println!("{:?}", r);
    r
}

fn main() {
    input! {
        d: usize,
        g: i32,
        v: [(i32, i32); d],
    }
    let res = func(d, g, &v).unwrap();
    println!("{}", res);
}


macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let mut s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};

    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };

    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };

    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };

    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };

    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}
fn main() {
    input! {
        R: i32,
    }

    println!(
        "{}",
        if R < 1200 {
            "ABC"
        } else if R < 2400 {
            "ARC"
        } else {
            "AGC"
        }
    );
}


switch Int(readLine()!)!{case 0..<1200:print("ABC");case 1200..<2800:print("ARC");default:print("AGC")}


var input:String? = readLine()
var numString:String = input!
var num = Int(numString)

if num < 1200{
  print("ABC")
}else if num<2800{
  print("ARC")
}else {
  print("AGC")
}


let R=Int(readLine()!)!
if R<1200{
  print("ABC")
}
else if R<2800{
  print("ARC")
}
else{
  print("AGC")
}


print(switch Int(readLine()!)!{case 0..<1200:"ABC";case 1200..<2800:"ARC";default:"AGC"})


var r = R
if r < 1200 {
    print("ABC")
} else if r < 2800 {
    print("ARC")
} else {
    print("AGC")
}


var input:String? = readLine()
var numstring:String = input!
var num = Int(input)

if num < 1200{
  print("ABC")
}else if num<2800{
  print("ARC")
}else {
  print("AGC")
}


const main = (input) => {
  input = input.split(' ');
  const a = parseInt(input[0], 10);

  if (a<1200) {
    console.log("ABC");
  }else if (a<2800) {
    console.log("ARC");
  }else{
    console.log("AGC");
  }
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


declare var require: (x: string) => any;

function Main(input: string[]) {
  const r = parseInt(input[0]);

  console.log((r < 1200) ? 'ABC' : (r < 2800) ? 'ARC' : 'AGC');
}

Main(require('fs').readFileSync('/dev/stdin', 'utf8').split('\n'));


const stdin = require('fs').readFileSync('/dev/stdin', 'utf8')

const _r = stdin.split('\n')[0]

const r = Number(_r)

let res = 'AGC'
if (r < 1200) {
  res = 'ABC'
} else if (r < 2800) {
  res = 'ARC'
}

console.log(res)


st main = (input) => {
  input = input.trim();
  const a = parseInt(input[0], 10);

  if (a<1200) {
    console.log("ABC");
  }else if (a<1200&&a<2800) {
    console.log("ARC");
  }else{
    console.log("AGC");
  }
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


const main = (input) => {
  const a = parseInt(input[0], 10);

  if (a<1200) {
    console.log("ABC");
  }else if (a<1200&&a<2800) {
    console.log("ARC");
  }else{
    console.log("AGC");
  }
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


const main = (input) => {
  input = input.split('');
  const a = parseInt(input[0], 10);

  if (a<1200) {
    console.log("ABC");
  }else if (a<1200&&a<2800) {
    console.log("ARC");
  }else{
    console.log("AGC");
  }
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


X, K, D = [abs(int(i)) for i in input().strip().split(' ')]

tmp = X // D
d1 = X - (D * tmp)
d2 = X - (D * (tmp + 1))

if tmp >= K:
  ans = X - (D * K)
else:
  if (tmp % 2) ^ (K % 2) == 0:
    ans = d1
  else:
    ans = d2

print(abs(ans))


X,K,D=map(int,input().split())
X=abs(X)
s=X//D
if s>=K:
  print(X-(D*K))
  exit()
n=K-s
n=n%2
if n==0:
  print(X-(D*s))
  exit()
else:
  print(abs(X-(D*s)-D))
  exit()


X,K,D=map(int,input().split())
X=abs(X)
if K*D<X:
    print(X-K*D)
else:
    K-=X//D
    X%=D
    if K%2==0:
        print(X)
    else:
        print(D-X)


X,K,D = map(int,input().split())

if X%2 == K%2==0:
    print(X)
elif X%2 != 0 and K%2==0:
    print(abs(X-(K//2)*D))
else:
    print(abs(X-((K//2)+1)*D))


X,K,D = map(int,input().split())

if K%2==0:
    print(abs(X-(K//2)*D))
else:
    print(abs(X-((K//2)+1)*D))


x,k,d=list(map(int,input().split()))
b=100000000000
for i in range(1,k+1):
  a=abs(x-k*d+8*i)
  b=min(b,a)
print(b)


import java.io.*;
import java.util.*;

public class Main {
    public static void main(final String[] args) {
        final FastReader s=new FastReader();
        long x = Math.abs(s.nextLong());
        long k = s.nextLong();
        long d = s.nextLong();

        long min = x/d;

        if(min>k){
            System.out.println(x-(k*d));
            return;
        }
        k=k-(x/d);
        x=x-(d*(x/d));

        if(k%2!=0) x = d-x;

        System.out.println(x);

    }

    static class FastReader
    {
        BufferedReader br;
        StringTokenizer st;
        public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); }
        String next() {
            while (st == null || !st.hasMoreElements()) {
                try { st = new StringTokenizer(br.readLine()); }
                catch (final IOException  e) { e.printStackTrace(); }
            }
            return st.nextToken();
        }
        int nextInt() { return Integer.parseInt(next()); }
        long nextLong() { return Long.parseLong(next()); }
        double nextDouble() { return Double.parseDouble(next()); }
        String nextLine() {
            String str = "";
            try { str = br.readLine(); }
            catch (final IOException e) { e.printStackTrace(); }
            return str;
        }
    }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        CWalkingTakahashi solver = new CWalkingTakahashi();
        solver.solve(1, in, out);
        out.close();
    }

    static class CWalkingTakahashi {
        public void solve(int testNumber, InputReader in, OutputWriter out) {

            long X = in.readLong(), K = in.readLong(), D = in.readLong();

            X = Math.abs(X);

            long moves = X / D;
            long mod = X % D;

            if (K <= moves) {
                out.printLine(X - (D * K));
            } else {

                if (K % 2 != moves % 2)
                    out.printLine(Math.abs(mod - D));
                else
                    out.printLine(mod);
            }

        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1) {
                throw new InputMismatchException();
            }
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0) {
                    return -1;
                }
            }
            return buf[curChar++];
        }

        public long readLong() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            long res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null) {
                return filter.isSpaceChar(c);
            }
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }

    static class OutputWriter {
        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void close() {
            writer.close();
        }

        public void printLine(long i) {
            writer.println(i);
        }

    }
}


import java.util.*;
import java.io.*;
public class Main{

    public static void main(String [] args) throws IOException{
        FastScanner sc=new FastScanner();
        long x=sc.nextLong();
        long k=sc.nextLong();
        long d=sc.nextLong();
        long need=(Math.abs(x)/d);

        if(need<=k){
            if(x<0){
                x+=need*d;
                k-=need;
                if(k%2==0){
                    System.out.println(Math.abs(x));
                }
                else{
                    System.out.println(Math.abs(x+d));
                }
            }
            else{
                x-=need*d;
                k-=need;
                if(k%2==0){
                    System.out.println(Math.abs(x));
                }
                else{
                    System.out.println(Math.abs(x-d));
                }
            }
        }
        else{
            if(x<0){
                System.out.println(Math.abs(x+k*d));
            }
            else{
                System.out.println(Math.abs(x-k*d));
            }
        }
    }

}

class FastScanner{
    private int BUFFER_SIZE = 1 << 16;

   private  DataInputStream din;

   private  byte[] buffer;

   private int bufferPointer, bytesRead;

   public FastScanner() {
       din = new DataInputStream(System.in);
       buffer = new byte[BUFFER_SIZE];
       bufferPointer = bytesRead = 0;
   }

   public FastScanner( String file_name) throws IOException {
       din = new DataInputStream(new FileInputStream(file_name));
       buffer = new byte[BUFFER_SIZE];
       bufferPointer = bytesRead = 0;
   }

   public String readLine() throws IOException {
        byte[] buf = new byte[64];
       int cnt = 0, c;
       while ((c = read()) != -1) {
           if (c == '\n')
               break;
           buf[cnt++] = (byte) c;
       }
       return new String(buf, 0, cnt);
   }

   public String next() throws IOException{

       byte c = read();
       while(Character.isWhitespace(c)){
           c = read();
       }

        StringBuilder builder = new StringBuilder();
       builder.append((char)c);
       c = read();
       while(!Character.isWhitespace(c)){
           builder.append((char)c);
           c = read();
       }

       return builder.toString();
   }

   public int nextInt() throws IOException {
       int ret = 0;
       byte c = read();
       while (c <= ' ')
           c = read();
        boolean neg = (c == '-');
       if (neg)
           c = read();
       do {
           ret = ret * 10 + c - '0';
       } while ((c = read()) >= '0' && c <= '9');

       if (neg)
           return -ret;
       return ret;
   }

   public int[] nextIntArray( int n) throws IOException {
        int arr[] = new int[n];
       for(int i = 0; i < n; i++){
           arr[i] = nextInt();
       }
       return arr;
   }

   public long nextLong() throws IOException {
       long ret = 0;
       byte c = read();
       while (c <= ' ')
           c = read();
        boolean neg = (c == '-');
       if (neg)
           c = read();
       do {
           ret = ret * 10 + c - '0';
       } while ((c = read()) >= '0' && c <= '9');
       if (neg)
           return -ret;
       return ret;
   }

   public long[] nextLongArray( int n) throws IOException {
        long arr[] = new long[n];
       for(int i = 0; i < n; i++){
           arr[i] = nextLong();
       }
       return arr;
   }

   public char nextChar() throws IOException{
       byte c = read();
       while(Character.isWhitespace(c)){
           c = read();
       }
       return (char) c;
   }

   public double nextDouble() throws IOException {
       double ret = 0, div = 1;
       byte c = read();
       while (c <= ' ')
           c = read();
        boolean neg = (c == '-');
       if (neg)
           c = read();

       do {
           ret = ret * 10 + c - '0';
       } while ((c = read()) >= '0' && c <= '9');

       if (c == '.') {
           while ((c = read()) >= '0' && c <= '9') {
               ret += (c - '0') / (div *= 10);
           }
       }

       if (neg)
           return -ret;
       return ret;
   }

   public double[] nextDoubleArray( int n) throws IOException {
        double arr[] = new double[n];
       for(int i = 0; i < n; i++){
           arr[i] = nextDouble();
       }
       return arr;
   }

   private void fillBuffer() throws IOException {
       bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
       if (bytesRead == -1)
           buffer[0] = -1;
   }

   private byte read() throws IOException {
       if (bufferPointer == bytesRead)
           fillBuffer();
       return buffer[bufferPointer++];
   }

   public void close() throws IOException {
       if (din == null)
           return;
       din.close();
   }

}


import java.util.Scanner;

/**
 * Created by enpingkuang on 2020/9/20 11:36 下午
 */
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        long x = scanner.nextLong();
        long k = scanner.nextLong();
        long d = scanner.nextLong();
        x = Math.abs(x);
        long n = x/d;
        if(n > k){
            System.out.println(x-k*d);
        }else{
            long tmp = k - n;
            if(tmp % 2 == 1){
                System.out.println(x - (n-1)*d);
            }else{
                System.out.println(Math.abs(x-n*d));
            }
        }
    }
}


import java.util.Scanner;

/**
 * Created by enpingkuang on 2020/9/20 11:36 下午
 */
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        long x = scanner.nextLong();
        long k = scanner.nextLong();
        long d = scanner.nextLong();
        long ans = 0;
        if(x <= 0){
            long n = -x/d;
            if(x%d !=0)n++;
            if(n > k){
                ans = Math.abs(x+k*d);
            }else{
                if((k - n)%2 == 0){
                    ans = Math.abs(x+n*d);
                }else{
                    ans = Math.abs(x+(n-1)*d);
                }
            }
        }else{
            long n = x/d;
            if(x%d !=0)n++;
            if(n > k){
                ans = Math.abs(x-k*d);
            }else{
                if((k - n)%2 == 0){
                    ans = x-n*d;
                }else{
                    ans = Math.abs(x-(n-1)*d);
                }
            }
        }
        System.out.println(ans);
    }
}


import java.util.*;
public class Main {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        String x_k_d [] = s.split(" ", -1);
        long x = Long.parseLong(x_k_d[0]);
        long k = Long.parseLong(x_k_d[1]);
        long d = Long.parseLong(x_k_d[2]);

        //移動した後の位置pos、残り移動回数a
        long pos = x;
        long a = k;
        long b = 0;
        long c = 0;

        //出力は絶対値なのでposを正にして計算する
        if(x < 0){
            pos *= -1;
        }
        //0に近づけるように移動させる
        if(x / d < k){
            a -= pos /d;
            pos = pos % d;

        }else{
            a = 0;
            pos -= d * k;
        }
        //System.out.println(pos);
        //System.out.println(a);

        if(a == 0){
            System.out.println(pos);
        }else{
            b = pos;
            c = (pos - d) * -1;
            if(a % 2 == 0){
                System.out.println(b);
            }else if(a % 2 == 1){
                System.out.println(c);
            }
        }
    }
}


#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef unsigned long long int llu;
typedef long double ld;
#define vi vector<int>
#define vl vector<ll>
#define vp vector<pair<int,int>>
#define pb push_back
#define pf push_front
#define mp map<ll,ll>
#define INF 1000000000000000000
#define fast ios_base::sync_with_stdio(false);cin.tie(NULL);
ll gcd(ll a,ll b)
{
    if(a==0)
    {
        return b;
    }
    else
    {
        return gcd(b%a,a);
    }
}
ll lcm(ll a,ll b)
{
    return a*b/gcd(a,b);
}
int f(char c)
{
    return (int)c-96;
}
/**********************************************************************
***********************************************************************
*********************ACTUAL CODE BEGINS HERE***************************/
int main()
{
    fast;
    ll x,k,d;
    cin>>x>>k>>d;
    x=abs(x);
    if(k<=(x/d))
        cout<<x-(k*d);
    else
    {
        k-=x/d;
        if(k%2)
            cout<<abs((x%d)-d);
        else
        {
            cout<<x%d;
        }

    }
    return 0;
}


#include "bits/stdc++.h"

using namespace std;
int main() {
	long long X, K, D;
	cin >> X >> K >> D;
	if (X < 0) {
		X = -X;
	}
	long long count = X / D;
	if (count >= K) {
		cout << X - K * D << endl;
		return 0;
	}
	if (1 == K%2) {
		long long x = X + D;
		cout << min(x % (2 * D), abs(2 * D - x % (2 * D))) << endl;
	}
	else {
		cout << min(X % (2 * D), abs(2 * D - X % (2 * D))) << endl;
	}
	return 0;
}


#include <bits/stdc++.h>
#define rep(i,n) for (int i = 0; i < (n); ++i)
using namespace std;
using ll = long long;
using P = pair<int,int>;

int main(){
	ll x,k,d;
	cin >> x >> k >> d;
	x = abs(x);
	ll ans = 0;
	if(x/d >= k){
		ans = x - d*k;
	}
	else{
		ll e = x/d;
		k -= e;
		x -= e*d;
		if(k%2 == 1) x = abs(x - d);
		ans = x;
	}
	cout << ans << endl;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll> l_l;
typedef pair<int, int> i_i;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define EPS (1e-7)
#define INF (1e9)
#define PI (acos(-1))
// #define debug(a) cout << "["; rep(i,a.size()) cout << a[i] << ", "; cout<<"]"<< endl;

const ll mod = 1000000007;

int main() {
    ll x, k, d; cin >> x >> k >> d;
    ll mostCloseX = x % d;
    ll needMove = abs(x % d - x) / d;
    if(needMove >= k) {
        if(x < 0){
            cout << x + d * k << endl;
        } else {
            cout << x - d * k << endl;
        }
        return 0;
    }
    ll leftMove = k - needMove;
    if(leftMove % 2 == 0){
        cout << abs(mostCloseX) << endl;
    } else {
        cout << min(abs(mostCloseX + d), abs(mostCloseX - d)) << endl;
    }
    return 0;
}


#include<bits/stdc++.h>

#define ntest 0

using namespace std;
long long x,k,d;
void solve()
{
    cin >> x >> k >> d;
    x = abs(x);
    if (x - k * d > 0)
    {
        cout << x - k * d;
    }
    else
    {
        long long tmpk = min(k,x / d);
        long long remain = k - tmpk;
        if (remain&1) cout << (tmpk+1)*d - x;
        else cout << x - tmpk * d;
    }

}
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    if(ntest)
    {
        int t;
        cin >> t;
        while(t--) solve();
    }
    else
    {
        solve();
    }

}


#include <bits/stdc++.h>
using namespace std;
using ll=long long;

int main(){
    ll x, k, d;
    cin >> x >> k >> d;
    ll a;

    if((x>0 && x-k*d>=0) || (x<0 && x-k*d<=0)){
        cout << abs(x-k*d) << endl;
    }else{
        a=x/d-x%d;
        x%=d;
        x=(x+d)%d;
        if(abs(x)<abs(x-d)){
            cout << abs(x) << endl;
        }else{
            cout << abs(x-d) << endl;
        }
    }

    return 0;
}


#include <stdio.h>
#include <stdlib.h>

int main(void) {
  long long int x, k, d;
  long long int q, r;
  scanf("%lld%lld%lld", &x, &k, &d);

  x = llabs(x);
  d = llabs(d);

  q = x/d;
  r = x%d;

  if (k <= q) {
    printf("%lld", x - d*k);
    return 0;
  }

  if ((k-q)%2==0) {
    printf("%lld", r);
    return 0;
  }

  if ((k-q)%2!=0) {
    printf("%lld", d-r);
    return 0;
  }
}


#include <stdio.h>

int main(){
  long long int X,K,D;
  scanf("%lld %lld %lld",&X,&K,&D);
  if(X<0LL) X=-X;
  if(X/D>=K) X-=K*D;
  else{
    long long int Y=X/D;
    K-=Y;
    X-=Y*D;
    if(K%2LL==1LL) X=D-X;
  }
  printf("%lld\n",X);
  return 0;
}


#include <stdio.h>

long long abs(long long A);
int main(void)
{
    long long X,K,D,M,q,r,ans=0;
    scanf("%lld %lld %lld",&X,&K,&D);
    X=abs(X);
    D=abs(D);
    q=X/D;
    r=X%D;

    M=K-q;

    if(M<=0){
        ans=X-K*D;
        // printf("A");
    } else {
        if(M%2==0){
            ans=X%D;
            // printf("B");
        } else {
            ans=abs(D-X%D);
            // printf("C");
        }
    }
    printf("%lld",ans);
    return 0;
}

long long abs(long long A)
{
    if(A<0) A=(-1)*A;
    return A;
}


#include <stdio.h>
#define abs(x) ((x > 0) ? x : -x)

int	main(void)
{
	long	X, K, D;
	int		i, j, sign = 1;

	scanf("%ld %ld %ld", &X, &K, &D);
	if (X < 0)
		sign = -1;
	i = (abs(X) + D - 1) / D;
	if (i > K)
		X -= sign * D * K;
	else
	{
		X -= sign * D * i;
		if (i < K && (K - i) % 2)
			X += sign * D;
	}
	printf("%ld\n", abs(X));
	return (0);
}


#include<stdio.h>
#pragma GCC optimize("Ofast")
int main(void){
  long long X,K,D;
  scanf("%lld%lld%lld",&X,&K,&D);
  long long i;
  long long j=0;
  for(i=1;i<=K;i++){
    if(X-D>=0)
      X = X - D;
    else{
      j = K - i;
      break;
    }
  }
  unsigned long long k=X;
  for(long long l=1;l<=j;l++){
    if(l % 2 == 1)
      k = k - D;
    else
      k = k + D;
  }
  printf("%lld",k);
  return 0;
}


#include <stdio.h>
#define abs(x) ((x > 0) ? x : -x)

int	main(void)
{
	long	X, K, D, i = 0;
	int		sign = 1;

	scanf("%ld %ld %ld", &X, &K, &D);
	if (X < 0)
		sign = -1;
	while (sign * X > 0 && i < K)
	{
		X -= sign * D;
		i++;
	}
	if ((K - i) % 2)
		X += sign * D;
	printf("%ld\n", abs(X));
	return (0);
}


const { SSL_OP_SSLEAY_080_CLIENT_DH_BUG } = require("constants");

function Main(input) {
  input = input.split("\n");
  var ans =0;
  var X = parseInt(input[0].split(" ")[0]);
  var K = parseInt(input[0].split(" ")[1]);
  var D = parseInt(input[0].split(" ")[2]);
  if(X<0){
    X=-X;
  }
  if(X==0){
    if(D%2==0){
      ans=0;
    }else{
      ans=K;
    }
  }else if(X>K*D){
    ans=X-K*D;
  }else{
    var a = Math.floor(X/D);
    var b = X%D;
    if((K-a)%2==0){
      ans=b;
    }else{
      ans=D-b;
    }
  }

  console.log('%s', ans);
  return ans;
}

function debug(n){
  var input = document.getElementById("input"+n).value;
  var ans=Main(input);
  var result="WA";
  if(ans==document.getElementById("output"+n).value.split("\n")[0]){
    result="AC";
  }
  document.getElementById("result"+n).innerHTML=result;
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(input) {
	const row = input.split(" ");
	const X = parseInt(row[0], 10);
	const K = parseInt(row[1], 10);
	const D = parseInt(row[2], 10);
	const even = num => num % 2 === 0;
	const av_x = X < 0 ? X * -1 : X;
	const cnt = av_x / D;

	if(cnt >= K) {
		console.log(av_x - K * D);
	} else {
		if(even(K - Math.floor(cnt))){
			console.log(av_x - D * Math.floor(cnt));
		} else {
			console.log(D * (Math.floor(cnt) + 1) - av_x);
		}
	}
};

Main(require("fs").readFileSync("/dev/stdin", "utf8"));


const input = require("fs").readFileSync("/dev/stdin", "utf8")
const lines = input.split('\n')
let [X, K, D] = lines[0].split(' ').map(Number)

X = Math.abs(X)
const div = Math.min(Math.floor(X / D), K)
let x = X - div * D
let k = K - div
for (let i = 0; i < k; i++) {
    x -= D
    if (x <= 0) {
        if (!((k - i) % 2)) {
            x += D
        }
        break
    }
}
console.log(Math.abs(x))


function Main(input) {
  const row = input.split(" ");
    	let X = parseInt(row[0], 10);
    	let K = parseInt(row[1], 10);
    	const D = parseInt(row[2], 10);
    let absX = Math.abs(X);
    let a = Math.floor(absX / D);
    let ans;

    if((absX /D) >= K) {
       ans = absX - D * K;

    } else {
       K2 = K - a;
       absX = absX - K2 * D;
       if(K2 % 2 === 1) {
    　ans = absX - D;
      } else {
         ans = absX;
      }
    } console.log(Math.abs(ans));
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(input) {
  const row = input.split(" ");
    	let X = parseInt(row[0], 10);
    	let K = parseInt(row[1], 10);
    	const D = parseInt(row[2], 10);
    let absX = Math.abs(X);
    let a = Math.floor(absX / D);
    let ans;

    // if((absX /D) >= K) {
    //    ans = absX - D * K;
    //
    // } else {
    //    K2 = K - a;
    //    absX = absX - K2 * D;
    //    if(K2 % 2 === 1) {
    // 　ans = absX - D;
    //   } else {
    //      ans = absX;
    //   }
    // } console.log(Math.abs(ans));
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));