use std::io;
use std::io::Stdin;
use std::str::FromStr;

fn read_line(stdin : &Stdin, line : &mut String) {
    match stdin.read_line(line) {
        Ok(_) => return,
        Err(msg) => panic!("Could not read line! Message: {}.", msg),
    }
}

fn parse_t<T : FromStr>(s : &str) -> T {
    match s.trim().parse() {
        Ok(y) => y,
        Err(_) => panic!("Could not read from string!"),
    }
}

fn read_t<T : FromStr>(stdin : &Stdin) -> T {
    let mut line = String::new();
    read_line(stdin, &mut line);
    parse_t(&line)
}

fn read_ts<T : FromStr>(stdin : &Stdin, ts : &mut Vec<T>) {
    let mut line = String::new();
    read_line(stdin, &mut line);
    let word_iter = line.split_whitespace();
    for word in word_iter {
        let x = parse_t(word);
        ts.push(x);
    }
}

fn cost_to_one(n : u64, k : u64, a : u64, b : u64) -> u64 {
    let mut c = 0;
    let mut x = n;
    loop {
        if x < 1 {
            panic!("x is less than 1!");
        } else if x == 1 {
            break;
        } else if x < k {
            c = c + (a * (x - 1));
            x = 1;
        } else {
            let q = x / k;
            let r = x % k;
            let cost_div = b;
            let cost_sub = a * ((q * k) - q);
            if r == 0 {
                if cost_div <= cost_sub {
                    c = c + cost_div;
                } else {
                    c = c + cost_sub;
                }
                x = q;
            } else {
                c = c + (r * a);
                x =  x - r;
            }
        }
    }
    c
}

fn main() {
    let stdin = io::stdin();
    let n = read_t(&stdin);
    let k = read_t(&stdin);
    let a = read_t(&stdin);
    let b = read_t(&stdin);
    println!("{}", cost_to_one(n, k, a, b));
}


#![allow(unused_imports)]
#![allow(unused_macros)]
// use proconio::input;
use std::cmp::Ordering::*;
use std::collections::{BTreeMap, BTreeSet};
use std::io::{self, BufWriter, Write};
use std::str::{self, SplitAsciiWhitespace};

// I have no idea what I'm doing

macro_rules! answer {
    ($out:ident, $ans:expr) => {
        writeln!($out, "{}", $ans)
    };
}

fn main() -> Result<(), io::Error> {
    let (stdin, stdout) = (io::stdin(), io::stdout());
    let mut scan = UnsafeScanner::new(stdin.lock());
    let mut out = BufWriter::new(stdout.lock());

    let n: i64 = scan.token();
    let mut ans: i64 = n + 1;

    for d in (2..=n).take_while(|d| d * d <= n) {
        if n % d == 0 {
            let p = n / d;
            ans = ans.min(d + p);
        }
    }

    answer!(out, ans)
}

///////////////////////////////////////////////////////////////////////////////////////////////////

/// Mostly copied from https://github.com/EbTech/rust-algorithms/blob/master/src/scanner.rs
/// Same API as Scanner but nearly twice as fast, using horribly unsafe dark arts
/// **REQUIRES** Rust 1.34 or higher
pub struct UnsafeScanner<R> {
    reader: R,
    buf_str: Vec<u8>,
    buf_iter: SplitAsciiWhitespace<'static>,
}

impl<R: io::BufRead> UnsafeScanner<R> {
    pub fn new(reader: R) -> Self {
        Self {
            reader,
            buf_str: vec![],
            buf_iter: "".split_ascii_whitespace(),
        }
    }

    /// This function should be marked unsafe, but noone has time for that in a
    /// programming contest. Use at your own risk!
    pub fn token<T: str::FromStr>(&mut self) -> T {
        loop {
            if let Some(token) = self.buf_iter.next() {
                return token.parse().ok().expect("Failed parse [Scanner]");
            }
            self.buf_str.clear();
            self.reader
                .read_until(b'\n', &mut self.buf_str)
                .expect("Failed read");
            self.buf_iter = unsafe {
                let slice = str::from_utf8_unchecked(&self.buf_str);
                std::mem::transmute(slice.split_ascii_whitespace())
            }
        }
    }

    pub fn pair<T: str::FromStr>(&mut self) -> (T, T) {
        (self.token(), self.token())
    }
}

// aka #![feature(bool_to_option)]
trait BoolThen {
    fn then_<T>(self, f: impl FnOnce() -> T) -> Option<T>;
}

impl BoolThen for bool {
    fn then_<T>(self, f: impl FnOnce() -> T) -> Option<T> {
        if self {
            Some(f())
        } else {
            None
        }
    }
}

trait BoolToYes {
    fn yes(self) -> &'static str;
}

impl BoolToYes for bool {
    fn yes(self) -> &'static str {
        if self {
            "YES"
        } else {
            "NO"
        }
    }
}


#[allow(unused_imports)]
use std::cmp::{max, min, Ordering};
#[allow(unused_imports)]
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};
#[allow(unused_imports)]
use std::io::{stdin, stdout, BufWriter, StdoutLock, Write};
#[allow(unused_imports)]
use std::iter::FromIterator;
#[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 , 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)]
pub fn with_bufwriter<F: FnOnce(BufWriter<StdoutLock>) -> ()>(f: F) {
    let out = stdout();
    let writer = BufWriter::new(out.lock());
    f(writer)
}
#[allow(unused_macros)]
macro_rules ! debug { ( $ ( $ a : expr ) ,* ) => { eprintln ! ( concat ! ( $ ( stringify ! ( $ a ) , " = {:?}, " ) ,* ) , $ ( $ a ) ,* ) } ; }
#[allow(dead_code)]
fn main() {
    input!{
        n: u64,
    }
    let mut i = 1;
    while i * i <= 1_000_000_000 {
        if i * i == n {
            println!("{}", i * 2);
            return;
        }
        if i * i > n {
            if n <= i * (i - 1) {
                println!("{}", i * 2 - 1);
            } else {
                println!("{}", i * 2);
            }
            return;
        }
        i += 1;
    }
}


use std::io;

fn main() {
  let mut input = String::new();
  io::stdin().read_line(&mut input).unwrap();

  let v = input.trim().chars().collect::<Vec<_>>();

  if v.len() % 2 == 0 {
    println!("CHAT WITH HER!");
  } else {
    println!("IGNORE HIM!");
  }
}


use std::io;

fn main() {
    let mut name = String::new();
    io::stdin().read_line(&mut name).expect("Error");
    let mut name_vector: Vec::<char> = name.trim().chars().collect();
    name_vector.sort();
    name_vector.dedup();
    let char_count = &name_vector.iter().count();
    let even = char_count % 2;
    if even == 0 {
        println!("CHAT WITH HERE!");
    } else {
        println!("IGNORE HIM!");
    }
}


//spnauti-rusT {{{
use std::io::*; use std::str::{self,*}; use std::fmt::Debug;
#[allow(unused_imports)] use std::cmp::Ordering::{self,*};
#[allow(unused_imports)] use std::ops::{self,*};
#[allow(unused_imports)] use std::iter::{self,*};
#[allow(unused_imports)] use std::collections::*;
#[allow(unused_imports)] use std::cell::*;
#[allow(unused_macros)] macro_rules! min {
	($x:expr,$y:expr) => {{ let b=$y; let a=&mut$x; if b < *a {*a=b; true} else {false} }};
}
#[allow(unused_macros)] macro_rules! max {
	($x:expr,$y:expr) => {{ let b=$y; let a=&mut$x; if b > *a {*a=b; true} else {false} }};
}
#[allow(unused_macros)] macro_rules! l {
	($($v:ident),+ =$e:expr) => {$(let$v=$e;)+};
	($($v:ident),+:$t:ty=$e:expr) => {$(let$v:$t=$e;)+};
	(mut $($v:ident),+ =$e:expr) => {$(let mut$v=$e;)+};
	(mut $($v:ident),+:$t:ty=$e:expr) => {$(let mut$v:$t=$e;)+};
}
#[allow(unused_macros)] macro_rules! v {
	([$d:expr]$($s:tt)+) => {vec![v!($($s)+);$d]};
	([]) => {Vec::new()}; ([$e:expr]) => {Vec::with_capacity($e)}; (=$e:expr) => {$e};
}
#[allow(unused_macros)] macro_rules! rep { {[$c:expr]$($s:tt)+} => {for _ in 0..$c {$($s)+}} }
#[allow(dead_code)] fn reader() -> WordReaderC { WordReaderC::new() }
#[allow(dead_code)] fn writer() -> BufWriter<Stdout> { BufWriter::new(stdout()) }
struct WordReaderC {buf: Vec<u8>, pos: usize, q: std::io::StdinLock<'static>}//'
#[allow(dead_code)] impl WordReaderC {
	fn new() -> Self {
		let r = unsafe {&*Box::into_raw(Box::new(stdin()))};
		Self { q: r.lock(), buf: Vec::new(), pos: 0 }
	}
	fn next_line(&mut self) -> bool {
		self.buf.clear(); self.pos = 0;
		self.q.read_until(b'\n', &mut self.buf).unwrap_or(0) > 0
	}
	fn is_ws(c: u8) -> bool {
		c == b' ' || c == b'\r' || c == b'\n' || c == b'\t'
	}
	fn byte(&mut self) -> Option<u8> {
		if self.pos == self.buf.len() { if !self.next_line() { return None; } }
		self.pos += 1; Some(self.buf[self.pos - 1])
	}
	fn vb(&mut self) -> Vec<u8> {
		let mut s = Vec::with_capacity(8);
		let mut f = false;
		loop {
			if let Some(c) = self.byte() {
				if !Self::is_ws(c) {
					s.push(c);
					f = true;
				} else if f { break; }
			} else { break; }
		}
		s
	}
	fn s(&mut self) -> String { String::from_utf8(self.vb()).expect("invalid utf8") }
	fn i(&mut self) ->    i32 { self.p() }
	fn l(&mut self) ->    i64 { self.p() }
	fn u(&mut self) ->  usize { self.p() }
	fn f(&mut self) ->    f64 { self.p() }
	fn vi(&mut self, n: usize) -> Vec<i32> { self.vp(n) }
	fn vl(&mut self, n: usize) -> Vec<i64> { self.vp(n) }
	fn vu(&mut self, n: usize) -> Vec<usize> { self.vp(n) }
	fn ii(&mut self, n: usize) -> impl Iterator<Item=i32> { self.ip(n).into_iter() }
	fn iu(&mut self, n: usize) -> impl Iterator<Item=usize> { self.ip(n).into_iter() }
	fn p<T: FromStr>(&mut self) -> T where T::Err: Debug {
		let w = self.vb(); str::from_utf8(w.as_ref()).unwrap().parse::<T>().unwrap()
	}
	fn vp<T: FromStr>(&mut self, n: usize) -> Vec<T> where T::Err: Debug {
		(0..n).map(|_|self.p()).collect()
	}
	fn ip<T: FromStr>(&mut self, n: usize) -> impl Iterator<Item=T> where T::Err: Debug {
		self.vp(n).into_iter()
	}
}
//------------------- End rusT }}}

fn main() {
	let mut rin = reader();
	let mut rout = writer();

	let n = rin.u();
	l!(x,y = rin.l());
	let mut dp = v!([n+1]);
	dp.push(x);
	dp.push(x);
	for i in 2..=n {
		let z = dp[i-1] + x;
		dp.push(z);
		if i & 1 == 0 {
			min!(dp[i], dp[i>>1] + y);
		}
	}
	writeln!(rout, "{}", dp[n]).ok();
}


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

macro_rules! debug(
    ($($arg:tt)*) => { {
        let r = writeln!(&mut ::std::io::stderr(), $($arg)*);
        r.expect("failed printing to stderr");
    } }
);

struct Scanner {
   buffer : std::collections::VecDeque<String>
}

impl Scanner {

   fn new() -> Scanner {
      Scanner {
         buffer: std::collections::VecDeque::new()
      }
   }

   fn next<T : std::str::FromStr >(&mut self) -> T {

      if self.buffer.len() == 0 {
         let mut input = String::new();
         std::io::stdin().read_line(&mut input).ok();
         for word in input.split_whitespace() {
            self.buffer.push_back(word.to_string())
         }
      }

      let front = self.buffer.pop_front().unwrap();
      front.parse::<T>().ok().unwrap()
   }
}

fn solve(dp : &mut Vec<u64>, n : usize, x : u64, y : u64) -> u64 {
   if n == 0 {
      0u64
   } else if n == 1 {
      x
   } else if dp[n] != 0 {
      dp[n]
   } else {
      let just_add = solve(dp, n-1, x, y) + x;
      let double_and_add = solve(dp, (n-1)/2, x, y) + x + y;
      let best = min(just_add, double_and_add);
      dp[n] = best;
      best
   }
}

fn main() {
   let mut s = Scanner::new();
   let n : usize = s.next();
   let x : u64 = s.next();
   let y : u64 = s.next();

   let mut dp : Vec<u64> = Vec::with_capacity(n + 1);
   dp.resize(n + 1, 0);

   println!("{}", solve(&mut dp, n, x, y));
}


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

macro_rules! debug(
    ($($arg:tt)*) => { {
        let r = writeln!(&mut ::std::io::stderr(), $($arg)*);
        r.expect("failed printing to stderr");
    } }
);

struct Scanner {
   buffer : std::collections::VecDeque<String>
}

impl Scanner {

   fn new() -> Scanner {
      Scanner {
         buffer: std::collections::VecDeque::new()
      }
   }

   fn next<T : std::str::FromStr >(&mut self) -> T {

      if self.buffer.len() == 0 {
         let mut input = String::new();
         std::io::stdin().read_line(&mut input).ok();
         for word in input.split_whitespace() {
            self.buffer.push_back(word.to_string())
         }
      }

      let front = self.buffer.pop_front().unwrap();
      front.parse::<T>().ok().unwrap()
   }
}

fn solve(dp : &mut Vec<u64>, n : usize, x : u64, y : u64) -> u64 {
   if n == 0 {
      0u64
   } else if n == 1 {
      x
   } else if dp[n] != 0 {
      dp[n]
   } else {
      let just_add = solve(dp, n-1, x, y) + x;
      let just_double = solve(dp, n/2, x, y) + y;
      let double_and_add = solve(dp, (n-1)/2, x, y) + x + y;
      let double_and_delete = solve(dp, (n+1)/2, x, y) + x + y;
      let mut best = min(just_add, min(double_and_add, double_and_delete));
      if n % 2 == 0 {
         best = min(best, just_double);
      }
      dp[n] = best;
      best
   }
}

fn main() {
   let mut s = Scanner::new();
   let n : usize = s.next();
   let x : u64 = s.next();
   let y : u64 = s.next();

   let mut dp : Vec<u64> = Vec::with_capacity(n + 1);
   dp.resize(n + 1, 0);

   println!("{}", solve(&mut dp, n, x, y));
}


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

macro_rules! debug(
    ($($arg:tt)*) => { {
        let r = writeln!(&mut ::std::io::stderr(), $($arg)*);
        r.expect("failed printing to stderr");
    } }
);

struct Scanner {
   buffer : std::collections::VecDeque<String>
}

impl Scanner {

   fn new() -> Scanner {
      Scanner {
         buffer: std::collections::VecDeque::new()
      }
   }

   fn next<T : std::str::FromStr >(&mut self) -> T {

      if self.buffer.len() == 0 {
         let mut input = String::new();
         std::io::stdin().read_line(&mut input).ok();
         for word in input.split_whitespace() {
            self.buffer.push_back(word.to_string())
         }
      }

      let front = self.buffer.pop_front().unwrap();
      front.parse::<T>().ok().unwrap()
   }
}

fn main() {
   let mut s = Scanner::new();
   let input : String = s.next();
   println!("8");
}


#[allow(unused_imports)]
use std::cmp::{max, min, Ordering};
#[allow(unused_imports)]
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};
#[allow(unused_imports)]
use std::io::{stdin, stdout, BufWriter, StdoutLock, Write};
#[allow(unused_imports)]
use std::iter::FromIterator;
#[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 , 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)]
pub fn with_bufwriter<F: FnOnce(BufWriter<StdoutLock>) -> ()>(f: F) {
    let out = stdout();
    let writer = BufWriter::new(out.lock());
    f(writer)
}
#[allow(unused_macros)]
macro_rules ! debug { ( $ ( $ a : expr ) ,* ) => { eprintln ! ( concat ! ( $ ( stringify ! ( $ a ) , " = {:?}, " ) ,* ) , $ ( $ a ) ,* ) } ; }
#[allow(dead_code)]
fn main() {
    input!{
        n: usize,
        a: [i64; n],
    }
    let mut can = false;
    for bit in 0..1<<n {
        let mut sum = 0;
        for i in 0..n {
            if bit & (1<<i) != 0 {
                sum += a[i];
            } else {
                sum -= a[i];
            }
        }
        if sum == 0 || sum == 360 || sum == -360 {
            can = true;
            break;
        }
    }
    if can {
        println!("YES");
    } else {
        println!("NO");
    }
}


// use rand::Rng;

use std::collections::*;
use std::io;

fn trim_newline(s: &mut String) {
    if s.ends_with('\n') {
        s.pop();
        if s.ends_with('\r') {
            s.pop();
        }
    }
}
macro_rules! parse_input {
    ($t:ident) => {{
        let mut input_line = String::new();
        io::stdin().read_line(&mut input_line).unwrap();
        trim_newline(&mut input_line);
        input_line.parse::<$t>().unwrap()
    }};
}

macro_rules! split_input {
    ($t:ident) => {{
        parse_input!(String)
            .split(" ")
            .map(|z| z.parse::<$t>().unwrap())
            .collect::<Vec<$t>>()
    }};
}

fn main() {
    let a = parse_input!(usize);
    let b = parse_input!(usize);
    let c = parse_input!(usize);
    let mut m = vec![a, b, c];
    m.sort();
    m.reverse();
    while *m.last().unwrap() == 1 {
        let p = m.pop().unwrap();
        *m.last_mut().unwrap() += p;
    }
    let mut ans = 1;
    for p in m {
        ans *= p;
    }
    println!("{}", ans);
}


use std::io;

fn main() {
    let mut a = String::new();
    let mut b = String::new();
    let mut c = String::new();

    io::stdin().read_line(&mut a).unwrap();
    io::stdin().read_line(&mut b).unwrap();
    io::stdin().read_line(&mut c).unwrap();

    let a: u8 = a.trim().parse().unwrap();
    let b: u8 = b.trim().parse().unwrap();
    let c: u8 = c.trim().parse().unwrap();

    let mut max_value = 0;

    if (a + b + c) > max_value {
        max_value = a + b + c;
    }
    if (a * b * c) > max_value {
        max_value = a * b * c;
    }
    if (a * b + c) > max_value {
        max_value = a * b + c;
    }
    if (a + b * c) > max_value {
        max_value = a + b * c;
    }

    if ((a + b) * c) > max_value {
        max_value = (a + b) * c;
    }
    if (a * (b + c)) > max_value {
        max_value = a * (b + c);
    }

    if (a + (b * c)) > max_value {
        max_value = a + (b * c);
    }
    if ((a * b) + c) > max_value {
        max_value = (a * b) + c;
    }

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


use crate::mod_int::ModInt;

const MOD: u64 = 998244353;

fn main() {
    let (r, w) = (std::io::stdin(), std::io::stdout());
    let mut sc = IO::new(r.lock(), w.lock());
    let n: u64 = sc.read();
    let m: u64 = sc.read();

    let comb = Combination::new(m, MOD);
    if n == 2 {
        println!("{}", m);
        return;
    }
    let c = mint(comb.get(m, n - 1));
    let ans = c * (n - 2) * mint(2).pow(n - 3);
    println!("{}", ans.value());
}

fn mint(v: u64) -> ModInt<u64> {
    ModInt::new(v, MOD)
}
pub mod mod_int {
    use std::ops::{
        Add, AddAssign, BitAnd, Div, DivAssign, Mul, MulAssign, RemAssign, ShrAssign, Sub,
        SubAssign,
    };

    pub struct ModInt<T> {
        v: T,
        m: T,
    }

    impl<T> ModInt<T>
    where
        T: Copy,
    {
        pub fn value(&self) -> T {
            self.v
        }
        pub fn modulo(&self) -> T {
            self.m
        }
    }

    impl<T> ModInt<T> {
        fn new_unchecked(v: T, modulo: T) -> Self {
            Self { v, m: modulo }
        }
    }

    impl<T> ModInt<T>
    where
        T: Copy + RemAssign + PartialOrd,
    {
        pub fn new(mut v: T, modulo: T) -> Self {
            if v >= modulo {
                v %= modulo;
            }
            Self::new_unchecked(v, modulo)
        }
    }

    impl<T> ModInt<T>
    where
        T: Copy
            + Sub<Output = T>
            + ShrAssign
            + BitAnd<Output = T>
            + PartialEq
            + PartialOrd
            + Div<Output = T>
            + RemAssign,
        ModInt<T>: MulAssign,
    {
        pub fn pow(self, e: T) -> Self {
            let zero = self.modulo() - self.modulo();
            let one = self.modulo() / self.modulo();
            let mut e = e;
            let mut result = Self::new_unchecked(one, self.modulo());
            let mut cur = self;
            while e > zero {
                if e & one == one {
                    result *= cur;
                }
                e >>= one;
                cur *= cur;
            }
            result
        }
    }

    impl<T> Copy for ModInt<T> where T: Copy {}
    impl<T> Clone for ModInt<T>
    where
        T: Copy,
    {
        fn clone(&self) -> Self {
            Self::new_unchecked(self.value(), self.modulo())
        }
    }

    impl<T> Add<T> for ModInt<T>
    where
        T: AddAssign + SubAssign + RemAssign + Copy + PartialOrd,
    {
        type Output = Self;
        fn add(self, mut rhs: T) -> Self::Output {
            if rhs >= self.modulo() {
                rhs %= self.modulo();
            }
            rhs += self.value();
            if rhs >= self.modulo() {
                rhs -= self.modulo();
            }
            Self::new_unchecked(rhs, self.modulo())
        }
    }

    impl<T> Sub<T> for ModInt<T>
    where
        T: AddAssign + SubAssign + RemAssign + Copy + PartialOrd,
    {
        type Output = Self;
        fn sub(self, mut rhs: T) -> Self::Output {
            if rhs >= self.modulo() {
                rhs %= self.modulo();
            }

            let mut result = self.value();
            result += self.modulo();
            result -= rhs;

            if result >= self.modulo() {
                result -= self.modulo();
            }
            Self::new_unchecked(result, self.modulo())
        }
    }

    impl<T> Mul<T> for ModInt<T>
    where
        T: MulAssign + RemAssign + Copy + PartialOrd,
    {
        type Output = Self;
        fn mul(self, mut rhs: T) -> Self::Output {
            if rhs >= self.modulo() {
                rhs %= self.modulo();
            }
            rhs *= self.value();
            rhs %= self.modulo();
            Self::new_unchecked(rhs, self.modulo())
        }
    }

    impl<T> Add<ModInt<T>> for ModInt<T>
    where
        T: Copy,
        ModInt<T>: Add<T, Output = ModInt<T>>,
    {
        type Output = Self;
        fn add(self, rhs: ModInt<T>) -> Self::Output {
            self + rhs.value()
        }
    }
    impl<T> Sub<ModInt<T>> for ModInt<T>
    where
        T: Copy,
        ModInt<T>: Sub<T, Output = ModInt<T>>,
    {
        type Output = Self;
        fn sub(self, rhs: ModInt<T>) -> Self::Output {
            self - rhs.value()
        }
    }
    impl<T> Mul<ModInt<T>> for ModInt<T>
    where
        T: Copy,
        ModInt<T>: Mul<T, Output = ModInt<T>>,
    {
        type Output = Self;
        fn mul(self, rhs: ModInt<T>) -> Self::Output {
            self * rhs.value()
        }
    }
    impl<T> Div<ModInt<T>> for ModInt<T>
    where
        T: Copy,
        ModInt<T>: Div<T, Output = ModInt<T>>,
    {
        type Output = Self;
        fn div(self, rhs: ModInt<T>) -> Self::Output {
            self / rhs.value()
        }
    }

    impl<T> AddAssign<T> for ModInt<T>
    where
        T: Copy,
        ModInt<T>: Add<T, Output = ModInt<T>>,
    {
        fn add_assign(&mut self, other: T) {
            *self = *self + other;
        }
    }
    impl<T> AddAssign<ModInt<T>> for ModInt<T>
    where
        T: Copy,
        ModInt<T>: Add<ModInt<T>, Output = ModInt<T>>,
    {
        fn add_assign(&mut self, other: ModInt<T>) {
            *self = *self + other;
        }
    }

    impl<T> SubAssign<T> for ModInt<T>
    where
        T: Copy,
        ModInt<T>: Sub<T, Output = ModInt<T>>,
    {
        fn sub_assign(&mut self, other: T) {
            *self = *self - other;
        }
    }

    impl<T> SubAssign<ModInt<T>> for ModInt<T>
    where
        T: Copy,
        ModInt<T>: Sub<ModInt<T>, Output = ModInt<T>>,
    {
        fn sub_assign(&mut self, other: ModInt<T>) {
            *self = *self - other;
        }
    }

    impl<T> DivAssign<T> for ModInt<T>
    where
        T: Copy,
        ModInt<T>: Div<T, Output = ModInt<T>>,
    {
        fn div_assign(&mut self, rhs: T) {
            *self = *self / rhs
        }
    }
    impl<T> DivAssign<ModInt<T>> for ModInt<T>
    where
        T: Copy,
        ModInt<T>: Div<ModInt<T>, Output = ModInt<T>>,
    {
        fn div_assign(&mut self, rhs: ModInt<T>) {
            *self = *self / rhs
        }
    }

    impl<T> MulAssign<T> for ModInt<T>
    where
        T: Copy,
        ModInt<T>: Mul<T, Output = ModInt<T>>,
    {
        fn mul_assign(&mut self, rhs: T) {
            *self = *self * rhs;
        }
    }

    impl<T> MulAssign<ModInt<T>> for ModInt<T>
    where
        T: Copy,
        ModInt<T>: Mul<ModInt<T>, Output = ModInt<T>>,
    {
        fn mul_assign(&mut self, rhs: ModInt<T>) {
            *self = *self * rhs;
        }
    }

    impl<T> Div<T> for ModInt<T>
    where
        T: Copy
            + Add<Output = T>
            + Sub<Output = T>
            + Div<Output = T>
            + BitAnd<Output = T>
            + PartialEq
            + PartialOrd
            + ShrAssign
            + RemAssign
            + MulAssign,
    {
        type Output = Self;
        fn div(self, mut rhs: T) -> Self::Output {
            if rhs >= self.modulo() {
                rhs %= self.modulo();
            }
            let one = self.modulo() / self.modulo();
            let two = one + one;
            self * Self::new_unchecked(rhs, self.modulo()).pow(self.modulo() - two)
        }
    }
}

pub struct Combination {
    fact: Vec<u64>,
    inv_fact: Vec<u64>,
    modulo: u64,
}

impl Combination {
    pub fn new(max: u64, modulo: u64) -> Self {
        let mut inv = vec![0; max as usize + 1];
        let mut fact = vec![0; max as usize + 1];
        let mut inv_fact = vec![0; max as usize + 1];
        inv[1] = 1;
        for i in 2..(max + 1) {
            inv[i as usize] = inv[(modulo % i) as usize] * (modulo - modulo / i) % modulo;
        }
        fact[0] = 1;
        inv_fact[0] = 1;
        for i in 0..max {
            fact[i as usize + 1] = fact[i as usize] * (i + 1) % modulo;
        }
        for i in 0..max {
            inv_fact[i as usize + 1] = inv_fact[i as usize] * inv[i as usize + 1] % modulo;
        }
        Self {
            fact,
            inv_fact,
            modulo,
        }
    }

    pub fn get(&self, x: u64, y: u64) -> u64 {
        assert!(x >= y);
        self.fact[x as usize] * self.inv_fact[y as usize] % self.modulo
            * self.inv_fact[x as usize - y as usize]
            % self.modulo
    }
}

pub struct IO<R, W: std::io::Write>(R, std::io::BufWriter<W>);

impl<R: std::io::Read, W: std::io::Write> IO<R, W> {
    pub fn new(r: R, w: W) -> Self {
        Self(r, std::io::BufWriter::new(w))
    }
    pub fn write<S: ToString>(&mut self, s: S) {
        use std::io::Write;
        self.1.write_all(s.to_string().as_bytes()).unwrap();
    }
    pub fn read<T: std::str::FromStr>(&mut self) -> T {
        use std::io::Read;
        let buf = self
            .0
            .by_ref()
            .bytes()
            .map(|b| b.unwrap())
            .skip_while(|&b| b == b' ' || b == b'\n' || b == b'\r' || b == b'\t')
            .take_while(|&b| b != b' ' && b != b'\n' && b != b'\r' && b != b'\t')
            .collect::<Vec<_>>();
        unsafe { std::str::from_utf8_unchecked(&buf) }
            .parse()
            .ok()
            .expect("Parse error.")
    }
    pub fn vec<T: std::str::FromStr>(&mut self, n: usize) -> Vec<T> {
        (0..n).map(|_| self.read()).collect()
    }
    pub fn chars(&mut self) -> Vec<char> {
        self.read::<String>().chars().collect()
    }
}


fn main() {
    use std::io::prelude::*;
    use std::io;

    let mut input = String::new();
    io::stdin().read_to_string(&mut input).unwrap();

    let necklace: Vec<_> = input.trim().chars().map(|c| {
        match c {
            '-' => Elem::Link,
            'o' => Elem::Pearl,
            _ => panic!("Invalid input"),
        }
    }).collect();

    let link_pearl_sums = necklace.iter().fold((0, 0), |acc, &e| {
        match e {
            Elem::Link => (acc.0 + 1, acc.1),
            Elem::Pearl => (acc.0, acc.1 + 1),
        }
    });

    let ans = link_pearl_sums.0 % link_pearl_sums.1 == 0;

    if ans {
        println!("YES");
    } else {
        println!("NO");
    }
}

#[derive(Clone, Copy)]
enum Elem {
    Link,
    Pearl
}


use std::io;

#[cfg(debug_assertions)]
macro_rules! debug_println {
    ($( $args:expr ),*) => { println!( $( $args ),* ); }
}

fn main() {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    let (l, p) = buf.chars().fold((0, 0), |mut cnt, v| {
        match v {
            '-' => cnt.0 += 1,
            'o' => cnt.1 += 1,
            _ => (),
        }
        cnt
    });
    debug_println!("{:?}", (l, p));
    println!("{}", if l % p == 0 { "YES" } else { "NO" });
}


use std::io;

macro_rules! debug_println {
    ($( $args:expr ),*) => { if cfg!(debug_assertions) { println!( $( $args ),* ); }}
}

fn main() {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    let (l, p) = buf.chars().fold((0, 0), |mut cnt, v| {
        match v {
            '-' => cnt.0 += 1,
            'o' => cnt.1 += 1,
            _ => (),
        }
        cnt
    });
    debug_println!("{:?}", (l, p));
    println!("{}", if l % p == 0 { "YES" } else { "NO" });
}


//spnauti-rusT {{{
use std::io::*; use std::str::{self,*}; use std::fmt::Debug;
#[allow(unused_imports)] use std::cmp::Ordering::{self,*};
#[allow(unused_imports)] use std::ops::{self,*};
#[allow(unused_imports)] use std::iter::{self,*};
#[allow(unused_imports)] use std::collections::*;
#[allow(unused_imports)] use std::cell::*;
#[allow(unused_macros)] macro_rules! min {
	($x:expr,$y:expr) => {{ let b=$y; let a=&mut$x; if b < *a {*a=b; true} else {false} }};
}
#[allow(unused_macros)] macro_rules! max {
	($x:expr,$y:expr) => {{ let b=$y; let a=&mut$x; if b > *a {*a=b; true} else {false} }};
}
#[allow(unused_macros)] macro_rules! l {
	($($v:ident),+ =$e:expr) => {$(let$v=$e;)+};
	($($v:ident),+:$t:ty=$e:expr) => {$(let$v:$t=$e;)+};
	(mut $($v:ident),+ =$e:expr) => {$(let mut$v=$e;)+};
	(mut $($v:ident),+:$t:ty=$e:expr) => {$(let mut$v:$t=$e;)+};
}
#[allow(unused_macros)] macro_rules! v {
	([$d:expr]$($s:tt)+) => {vec![v!($($s)+);$d]};
	([]) => {Vec::new()}; ([$e:expr]) => {Vec::with_capacity($e)}; (=$e:expr) => {$e};
}
#[allow(unused_macros)] macro_rules! rep { {[$c:expr]$($s:tt)+} => {for _ in 0..$c {$($s)+}} }
#[allow(dead_code)] fn reader() -> WordReaderC { WordReaderC::new() }
#[allow(dead_code)] fn writer() -> BufWriter<Stdout> { BufWriter::new(stdout()) }
struct WordReaderC {buf: Vec<u8>, pos: usize, q: std::io::StdinLock<'static>}//'
#[allow(dead_code)] impl WordReaderC {
	fn new() -> Self {
		let r = unsafe {&*Box::into_raw(Box::new(stdin()))};
		Self { q: r.lock(), buf: v!([]), pos: 0 }
	}
	fn next_line(&mut self) -> bool {
		self.buf.clear(); self.pos = 0;
		self.q.read_until(b'\n', &mut self.buf).unwrap_or(0) > 0
	}
	fn is_ws(c: u8) -> bool {
		c == b' ' || c == b'\r' || c == b'\n' || c == b'\t'
	}
	fn byte(&mut self) -> Option<u8> {
		if self.pos == self.buf.len() { if !self.next_line() { return None; } }
		self.pos += 1; Some(self.buf[self.pos - 1])
	}
	fn vb(&mut self) -> Vec<u8> {
		let mut s = v!([8]);
		let mut f = false;
		loop {
			if let Some(c) = self.byte() {
				if !Self::is_ws(c) {
					s.push(c);
					f = true;
				} else if f { break; }
			} else { break; }
		}
		s
	}
	fn board(&mut self, r: usize, c: Option<usize>) -> Vec<Vec<u8>> {
		let mut res = v!([r]);
		let c = c.unwrap_or(0);
		rep!{[r]
			let t = self.vb();
			assert!(c == 0 || t.len() == c);
			res.push(t);
		}
		res
	}
	fn framed_board(&mut self, r: usize, c: usize, f: u8) -> Vec<Vec<u8>> {
		let mut res = v!([r+2]);
		res.push( v!([c+2] = f) );
		rep!{[r]
			let mut t = self.vb();
			assert!(t.len() == c);
			t.reserve(2);
			t.insert(0,f);
			t.push(f);
			res.push(t);
		}
		res.push( v!([c+2] = f) );
		res
	}
	fn s(&mut self) -> String { String::from_utf8(self.vb()).expect("invalid utf8") }
	fn i(&mut self) ->    i32 { self.p() }
	fn l(&mut self) ->    i64 { self.p() }
	fn u(&mut self) ->  usize { self.p() }
	fn f(&mut self) ->    f64 { self.p() }
	fn vi(&mut self, n: usize) -> Vec<i32> { self.vp(n) }
	fn vl(&mut self, n: usize) -> Vec<i64> { self.vp(n) }
	fn vu(&mut self, n: usize) -> Vec<usize> { self.vp(n) }
	fn ii(&mut self, n: usize) -> impl Iterator<Item=i32> { self.ip(n).into_iter() }
	fn iu(&mut self, n: usize) -> impl Iterator<Item=usize> { self.ip(n).into_iter() }
	fn p<T: FromStr>(&mut self) -> T where T::Err: Debug {
		let w = self.vb(); str::from_utf8(w.as_ref()).unwrap().parse::<T>().unwrap()
	}
	fn vp<T: FromStr>(&mut self, n: usize) -> Vec<T> where T::Err: Debug {
		(0..n).map(|_|self.p()).collect()
	}
	fn ip<T: FromStr>(&mut self, n: usize) -> impl Iterator<Item=T> where T::Err: Debug {
		self.vp(n).into_iter()
	}
	fn graph(&mut self, n: usize, m: usize) -> Vec<Vec<usize>> {
		let mut e = v!([n][]); rep!{[m] l!(a,b = self.u()-1); e[a].push(b); e[b].push(a); } e
	}
	fn graph_w<T: Copy+FromStr>(&mut self, n: usize, m: usize) -> Vec<Vec<(usize,T)>> where T::Err: Debug {
		let mut e = v!([n][]); rep!{[m] l!(a,b = self.u()-1); let c: T = self.p(); e[a].push((b,c)); e[b].push((a,c)); } e
	}
}
//------------------- End rusT }}}

fn main() {
	let mut rin = reader();
	let mut rout = writer();

	let b = rin.l();
	let s = rin.vb();
	let n = s.len();
	let mut dp = v!([n+1] = std::i64::MAX);
	dp[0] = 0;
	for i in 0..n {
		let mut x = 0;
		for j in i..n {
			x = x * 10 + (s[j] - b'0') as i64;
			if (s[i] == b'0' && j > i) || x >= b {
				break;
			}
			min!(dp[j+1], dp[i] * b + x);
		}
	}
	writeln!(rout, "{}", dp[n]).ok();
}


#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;
use std::io::*;
#[allow(dead_code)]
fn getline() -> String {
    let mut ret = String::new();
    std::io::stdin().read_line(&mut ret).ok();
    return ret;
}
fn get_word() -> String {
    let mut stdin = std::io::stdin();
    let mut u8b: [u8; 1] = [0];
    loop {
        let mut buf: Vec<u8> = Vec::with_capacity(16);
        loop {
            let res = stdin.read(&mut u8b);
            if res.is_err() || res.ok().unwrap() == 0 || u8b[0] <= ' ' as u8 {
                break;
            } else {
                buf.push(u8b[0]);
            }
        }
        if buf.len() >= 1 {
            let ret = std::string::String::from_utf8(buf).unwrap();
            return ret;
        }
    }
}
fn parse<T: std::str::FromStr>(s: &str) -> T { s.parse::<T>().ok().unwrap() }

#[allow(dead_code)]
fn get<T: std::str::FromStr>() -> T { parse(&get_word()) }

fn numero(v: &[i64], b: i64) -> i64 {
    let mut cur = 0;
    for &t in v.iter() {
        cur *= b;
        cur += t;
    }
    cur
}

fn main() {
    let b: i64 = get();
    let s: Vec<_> = get_word().bytes().map(|b| b as i64 - 0x30).collect();
    let n = s.len();
    if b <= 9 {
        // simply read b-base rep.
        let mut cur = 0;
        for v in s {
            cur *= b;
            cur += v;
        }
        println!("{}", cur);
        return;
    }
    let mut dp = vec![-1i64; n + 1];
    const INF: i64 = 1i64 << 60;
    dp[0] = 0;
    for i in 1 .. n + 1 {
        let mut mi = INF;
        for j in 1 .. i + 1 {
            // s[i - j ..i] < b ?
            if j >= 10 || dp[i - j] < 0 || (j >= 2 && s[i - j] == 0) ||
                numero(&s[i - j .. i], 10) >= b {
                continue;
            }
            mi = min(mi, b * dp[i - j] + numero(&s[i - j .. i], 10));
        }
        if mi < INF {
            dp[i] = mi;
        }
    }
    println!("{}", dp[n]);
}


use std::io;
use std::mem::swap;
use std::str;

fn has_valid_prime_factors(n: i64) -> bool {
    let mut n = n;
    while n % 2 == 0 {
        n /= 2;
    }
    while n % 3 == 0 {
        n /= 3;
    }
    while n % 5 == 0 {
        n /= 5;
    }
    n == 1
}

fn gcd(a: i64, b: i64) -> i64 {
    if b == 0 {
        a
    } else {
        gcd(b, a % b)
    }
}

fn factorize(n: i64) -> Vec<(i64, i64)> {
    let mut n = n;
    let mut p = 2;
    let mut ans = Vec::new();
    while p * p <= n && n > 1 {
        let mut expo = 0;
        while n % p == 0 {
            expo += 1;
            n /= p;
        }
        if expo > 0 {
            ans.push((p, expo));
        }
        p += 1;
    }
    if n > 1 {
        ans.push((n, 1));
    }
    ans
}

fn solve<R: io::BufRead, W: io::Write>(scan: &mut Scanner<R>, out: &mut W) {
    let mut a: i64 = scan.token();
    let mut b: i64 = scan.token();
    if a > b {
        swap(&mut a, &mut b);
    }

    // The factorizations of a and b MUST contain only prime factors in {2, 3, 5}.
    if a == b || (has_valid_prime_factors(a) && has_valid_prime_factors(b)) {
        let g = gcd(a, b);
        let factors_without_gcd = factorize(a * b / (g * g));
        let ans = factors_without_gcd.iter().fold(0i64, |acc, val| acc + val.1);
        writeln!(out, "{}", ans).ok();
    } else {
        writeln!(out, "-1").ok();
    }
}

fn main() {
    let (stdin, stdout) = (io::stdin(), io::stdout());
    let mut scan = Scanner::new(stdin.lock());
    let mut out = io::BufWriter::new(stdout.lock());
    solve(&mut scan, &mut out);
}

pub struct Scanner<R> {
    reader: R,
    buffer: Vec<String>,
}

impl<R: io::BufRead> Scanner<R> {
    pub fn new(reader: R) -> Self {
        Self {
            reader,
            buffer: vec![],
        }
    }

    pub fn token<T: str::FromStr>(&mut self) -> T {
        loop {
            if let Some(token) = self.buffer.pop() {
                return token.parse().ok().expect("Failed parse");
            }
            let mut input = String::new();
            self.reader.read_line(&mut input).expect("Failed read");
            self.buffer = input.split_whitespace().rev().map(String::from).collect();
        }
    }

    pub fn tokens<T: str::FromStr>(&mut self) -> Vec<T> {
        assert!(self.buffer.is_empty());
        let mut input = String::new();
        self.reader.read_line(&mut input).expect("Failed read");
        input
            .split_whitespace()
            .map(|x| x.parse().ok().expect("Failed parse"))
            .collect()
    }
}


use std::io::{self, BufWriter, Write};
use std::str::{self, SplitAsciiWhitespace};

// I have no idea what I'm doing

/// Copied from https://github.com/EbTech/rust-algorithms/blob/master/src/scanner.rs
/// Same API as Scanner but nearly twice as fast, using horribly unsafe dark arts
/// **REQUIRES** Rust 1.34 or higher
pub struct UnsafeScanner<R> {
    reader: R,
    buf_str: Vec<u8>,
    buf_iter: SplitAsciiWhitespace<'static>,
}

impl<R: io::BufRead> UnsafeScanner<R> {
    pub fn new(reader: R) -> Self {
        Self {
            reader,
            buf_str: vec![],
            buf_iter: "".split_ascii_whitespace(),
        }
    }

    /// This function should be marked unsafe, but noone has time for that in a
    /// programming contest. Use at your own risk!
    pub fn token<T: str::FromStr>(&mut self) -> T {
        loop {
            if let Some(token) = self.buf_iter.next() {
                return token.parse().ok().expect("Failed parse");
            }
            self.buf_str.clear();
            self.reader
                .read_until(b'\n', &mut self.buf_str)
                .expect("Failed read");
            self.buf_iter = unsafe {
                let slice = str::from_utf8_unchecked(&self.buf_str);
                std::mem::transmute(slice.split_ascii_whitespace())
            }
        }
    }

    pub fn pair<T: str::FromStr>(&mut self) -> (T, T) {
        (self.token(), self.token())
    }
}

fn main() -> Result<(), io::Error> {
    let (stdin, stdout) = (io::stdin(), io::stdout());
    let mut scan = UnsafeScanner::new(stdin.lock());
    let mut out = BufWriter::new(stdout.lock());

    let mut x: i32 = scan.token();
    let m: i32 = scan.token();

    let mut seen = vec![false; m as usize];

    while x > 0 && !seen[x as usize] {
        seen[x as usize] = true;
        x += x;
        if x >= m {
            x -= m;
        }
    }

    writeln!(out, "{}", match x {
        0 => "Yes",
        _ => "No",
    })?;

    Ok(())
}


//spnauti-rust
#[allow(unused_macros)]
macro_rules! a {
    ($c: tt, $x: expr, $y: expr) => {{
        let b = $y; let a = &mut $x;
        if b $c *a { *a = b; true } else { false }
    }};
}
use std::io::*;
use std::str::*;
use std::fmt::Debug;
struct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }
#[allow(dead_code)]
impl<'a> WordReader<'a> {
    fn new<T: Read>(b: &mut String, mut r: T) -> WordReader {
        b.clear();
        r.read_to_string(b).unwrap();
        WordReader { it: b.split_ascii_whitespace() }
    }
    fn from_stdin(b: &mut String) -> WordReader {
        WordReader::new(b, stdin())
    }
    fn sl(&mut self) ->  &str { self.it.next().unwrap() }
    fn bs(&mut self) -> &[u8] { self.sl().as_bytes()    }
    fn s(&mut self) -> String { String::from(self.sl()) }
    fn i(&mut self) ->    i32 { self.p()                }
    fn p<T: FromStr>(&mut self) -> T where T::Err: Debug {
        self.sl().parse::<T>().unwrap()
    }
    fn vp<T: FromStr>(&mut self, n: usize) -> Vec<T> where T::Err: Debug {
        (0..n).map(|_| self.p()).collect()
    }
}

fn main() {
    let mut bin = String::new();
    let mut input = WordReader::from_stdin(&mut bin);

    let (n,d) = (input.i(), input.i());
    let sum = d - input.vp::<i32>(n as usize)
        .into_iter().sum::<i32>();
    println!("{}", if sum >= 10 * (n - 1) {
        sum / 10
    } else {
        -1
    });
}


use std::io;
use std::collections::HashMap;

fn main() {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).expect("enter value");
    let charcount:usize = buf.trim().parse::<usize>().unwrap();
    buf.clear();
    io::stdin().read_line(&mut buf).expect("Enter value");
    let chars:Vec<_> = buf.chars().collect();
    let mut count = 0;
    let mut keymap: HashMap<char, i32> = HashMap::new();
    for x in 0..charcount{
        if x < chars.len() && chars[x] == chars[x+1] {
            count = count + 1;
        } else {
            if let Some(val) = keymap.get_mut(&chars[x]){
                *val += count;
            } else {
                keymap.insert(chars[x], count);
            }
            count = 0;
        }
    }
    let highvalue = keymap.iter().max_by_key(|entry| entry.1).unwrap();
    println!("{:?}", highvalue.1);
}


#![allow(unused_macros)]
#![allow(unused_mut)]

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

// credit tanakh input macro
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")
    };
}

// credit ebtech scanner
pub struct UnsafeScanner<R> {
    reader: R,
    buf_str: Vec<u8>,
    buf_iter: str::SplitAsciiWhitespace<'static>,
}

impl<R: io::BufRead> UnsafeScanner<R> {
    pub fn new(reader: R) -> Self {
        Self {
            reader,
            buf_str: vec![],
            buf_iter: "".split_ascii_whitespace(),
        }
    }

    /// This function should be marked unsafe, but noone has time for that in a
    /// programming contest. Use at your own risk!
    pub fn token<T: str::FromStr>(&mut self) -> T {
        loop {
            if let Some(token) = self.buf_iter.next() {
                return token.parse().ok().expect("Failed parse");
            }
            self.buf_str.clear();
            self.reader
                .read_until(b'\n', &mut self.buf_str)
                .expect("Failed read");
            self.buf_iter = unsafe {
                let slice = str::from_utf8_unchecked(&self.buf_str);
                std::mem::transmute(slice.split_ascii_whitespace())
            }
        }
    }
}

fn solve() {
    #[allow(unused_variables)]
    let (stdin, stdout) = (io::stdin(), io::stdout());
    //let mut scan = UnsafeScanner::new(stdin.lock());
    let mut out = io::BufWriter::new(stdout.lock());

    input! {
        a: usize,
        s: String,
    }
    let mut v = Vec::new();
    for c in s.chars() {
        v.push(c);
    }

    if a == 1 { writeln!(out, "{}", 0).ok();}
    else {
        let mut op = 0;
        for i in 0..(v.len() - 1) {
            if v[i] != v[i+1] {
                writeln!(out, "{}", op).ok();
                return;
            } else {
                op += 1;
            }
        }
        writeln!(out, "{}", op).ok();
    }

}

// credit kobae964
fn main() {
    // In order to avoid potential stack overflow, spawn a new thread.
    let stack_size = 104_857_600; // 100 MB
    let thd = std::thread::Builder::new().stack_size(stack_size);
    thd.spawn(|| solve()).unwrap().join().unwrap();
}


use std::io;

fn main() {
    let mut s = String::new();
    io::stdin().read_line(&mut s).unwrap();
    let n : i32 = s.trim().parse().unwrap();
    s.clear();
    io::stdin().read_line(&mut s).unwrap();
    s = s.trim().to_string();
    let mut cnt = 0;
    let mut before : char = 'x';
    for (i, c) in s.chars().enumerate() {
        if i == 0 {
            before = c;
        } else if c == before {
            cnt += 1;
        }
        before = c;
    }
    if cnt == n-1 {
        cnt += 1;
    }
    println!("{}", cnt);
}


fn main() -> std::io::Result<()> {
    let mut buffer = String::new();
    std::io::stdin().read_line(&mut buffer)?;
    let index: usize = buffer.trim().parse().unwrap();
    buffer.clear();

    std::io::stdin().read_line(&mut buffer)?;
    let mut count: i32 = 0;
    let mut ind: usize = 0;
    for i in 0..index-1 {
        if &buffer[ind..ind+1] == &buffer[i+1..i+2] {
            count += 1;
            continue;
        }
        ind += 1;
    }
    println!("{}", count);
    Ok(())
}


fn main() {
    let mut input = String::new();
        std::io::stdin()
                .read_line(&mut input)
                .expect("Value not found");

    let input :usize = match input
                            .trim()
                            .parse() {
                                Ok(num) => num,
                                Err(_) => return,
                            };

    let mut colors = String::new();
        std::io::stdin()
                        .read_line(&mut colors)
                        .expect("Value not found");

    let length = colors.trim().len();

    if length != input {
        return ()
    }

    let mut count: usize = 0;
    let mut i: usize = 0;
    for _i in colors.chars() {
        if colors.chars().nth(i) == colors.chars().nth(i+1) {
            count += 1;
            i += 1;
        }
    }
    println!("{}", count);

    // for i in 0usize..input {
    // }

    // for i in colors.chars().next() {
    //     match i {
    //           => count += 1,
    //         _  => return,
    //     };
    // }
    // println!("{}", count);

}


fn main() {
    let first_string = string_read();
    let second_string = string_read();

    let mut counter: i32 = 0;

    let mut first_chars = first_string.chars();
    let mut second_chars = second_string.chars();
    loop {
        match (first_chars.next(), second_chars.next()) {
            (Some(lchar), Some(rchar)) => {
                if lchar < rchar {counter -= 1}
                else if lchar > rchar {counter += 1}
            },
            (_, _) => {break;}
        }
    }
    println!("{}", counter);

}

fn string_read() -> String {
    let mut string_buffer = String::new();

    std::io::stdin().read_line(&mut string_buffer).unwrap();
    string_buffer.to_uppercase()
}


use std::cmp::Ordering;

fn main() {
    let mut line1 = String::new();
    let mut line2 = String::new();
    std::io::stdin().read_line(&mut line1).unwrap();
    std::io::stdin().read_line(&mut line2).unwrap();

    line1 = line1.trim().to_lowercase();
    line2 = line2.trim().to_lowercase();

    println!("{}", line1);
    println!("{}", line2);

    println!("{}",
        match  line1.cmp(&line2) {
            Ordering::Less => -1,
            Ordering::Equal => 0,
            Ordering::Greater => 1,
        });
}


fn main() {
    let mut first_string = String::from("");
            std::io::stdin()
                    .read_line(&mut first_string)
                    .expect("String not found");

    let mut second_string = String::from("");
            std::io::stdin()
                    .read_line(&mut second_string)
                    .expect("String not found");

    if (first_string.len() > 100) || (second_string.len() > 100) {
        return()
    }

    if first_string.len() != second_string.len() {
        return ()
    }

    let first_string = first_string.to_lowercase();
    let second_string = second_string.to_lowercase();

    // let comp1 = first_string.eq(&second_string);
    // let comp2 = second_string.eq(&first_string);

    if first_string == second_string { println!("0"); }

    else if first_string > second_string { println!("1"); }

    else if first_string < second_string { println!("-1"); }

    else { return () }

}


fn main() {
    let (r1, r2) = parse();
    let (c1, c2) = parse();
    let (d1, d2) = parse();
    let mut v1 = vec![];
    let mut v2 = vec![];

    for a in 1..10 {
        for b in 1..10 {
            if a != b && a + b == d1 {
                v1.push((a, b));
            }
            if a != b && a + b == d2 {
                v2.push((a, b))
            }
        }
    }
    for a in &v1 {
        for b in &v2 {
            if a.0 + b.0 == r1
                && a.1 + b.1 == r2
                && a.0 != b.0
                && a.0 != b.1
                && a.1 != b.0
                && a.1 != b.1
            {
                print_result(*a, *b);
                return;
            }
        }
    }
    println!("-1");
}
fn print_result(a: (usize, usize), b: (usize, usize)) {
    println!("{} {}", a.0, b.0);
    println!("{} {}", b.1, a.1)
}
fn parse() -> (usize, usize) {
    let mut text = String::new();
    std::io::stdin().read_line(&mut text).unwrap();
    let text: Vec<usize> = text
        .trim()
        .split_whitespace()
        .map(|e| e.parse().unwrap())
        .collect();
    (text[0], text[1])
}


use std::*;

fn main () {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    let a: i32 = buf.parse();
    println!("1");
}


use std::*;

fn main () {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    let a: i32 = buf.parse().unwrap();
    println!("1");
}


use std::*;

fn main () {
    // let mut buf = String::new();
    // io::stdin().read_line(&mut buf).unwrap();
    // let a: i32 = buf.parse().unwrap();
    println!("1");
}


use std::io;

fn main() {

	let mut input = String::new();

	io::stdin().read_line(&mut input);

	println!("1");
}


fn c2 (x:i32) -> i64 { let y=x as i64; y * (y-1)/2 }

fn main() {
  let mut s = String::new();
  std::io::stdin().read_line(&mut s).unwrap();
  let mut ints = s.split_whitespace().map(|x| x.parse::<i32>().unwrap());
  let n = ints.next().unwrap();
  let t = ints.next().unwrap();
  if n == t {
     println!("0 0");
  } else {
     let max = c2(n - t + 1);
     let mut min = 0;
     let mut m = n;
     for i in (2..=t).rev() {
        min += c2(m/i);
        m-=m/i;
     }
     min += c2(m);
     println!("{} {}",min, max);
  }

}


struct Scan {
    buffer: std::collections::VecDeque<String>
}

impl Scan {
    fn new() -> Scan {
        Scan { buffer: std::collections::VecDeque::new() }
    }

    fn next<T: std::str::FromStr>(&mut self)-> T {
        loop {
            if let Some(token) = self.buffer.pop_front() {
                break token.parse::<T>().ok().unwrap();
            }
            let mut line = String::new();
            std::io::stdin().read_line(&mut line).expect("Fail to read");
            self.buffer = line.split_whitespace().map(String::from).collect();
        }
    }

}

fn _main() {
    let mut scan = Scan::new();
    let n: u64 = scan.next();
    let m: u64 = scan.next();
    if n == m {
        println!("{} {}", m, m);
        return;
    }
    let maxcalc = (n-m+1) * (n-m) / 2;
    let minval1 = n/m + 1;
    let minval2 = n/m;
    let minn1 = n%m;
    let minn2 = m - minn1;
    let mincalc = (minval1*(minval1-1)/2)*minn1
        + (minval2*(minval2-1)/2)*minn2;
    println!("{} {}", mincalc, maxcalc);
}

fn main() {
    std::thread::Builder::new()
        .stack_size(1<<23).spawn(_main).unwrap().join().unwrap();
}


//---------- begin SegmentTree Point update Range query ----------
pub trait PURQ {
    type T: Clone;
    fn fold(l: &Self::T, r: &Self::T) -> Self::T;
    fn e() -> Self::T;
}

struct SegmentTreePURQ<R: PURQ> {
    seg: Vec<R::T>,
    size: usize,
}

#[allow(dead_code)]
impl<R: PURQ> SegmentTreePURQ<R> {
    fn new(n: usize) -> SegmentTreePURQ<R> {
        let size = n.next_power_of_two();
        SegmentTreePURQ {
            seg: vec![R::e(); 2 * size],
            size: size,
        }
    }
    fn build_by(a: &[R::T]) -> SegmentTreePURQ<R> {
        let size = a.len().next_power_of_two();
        let mut b = vec![R::e(); 2 * size];
        for i in 0..a.len() {
            b[i + size] = a[i].clone();
        }
        let mut seg = SegmentTreePURQ { seg: b, size: size };
        seg.update_all();
        seg
    }
    fn update(&mut self, x: usize, v: R::T) {
        assert!(x < self.size);
        let mut x = x + self.size;
        let a = &mut self.seg;
        a[x] = v;
        x >>= 1;
        while x > 0 {
            a[x] = R::fold(&a[2 * x], &a[2 * x + 1]);
            x >>= 1;
        }
    }
    fn update_tmp(&mut self, x: usize, v: R::T) {
        self.seg[self.size + x] = v;
    }
    fn update_all(&mut self) {
        let a = &mut self.seg;
        for i in (1..self.size).rev() {
            a[i] = R::fold(&a[2 * i], &a[2 * i + 1]);
        }
    }
    fn find(&self, l: usize, r: usize) -> R::T {
        assert!(l <= r && r <= self.size);
        let mut x = R::e();
        let mut y = R::e();
        let mut l = l + self.size;
        let mut r = r + self.size;
        let a = &self.seg;
        while l < r {
            if l & 1 == 1 {
                x = R::fold(&x, &a[l]);
                l += 1;
            }
            if r & 1 == 1 {
                r -= 1;
                y = R::fold(&a[r], &y);
            }
            l >>= 1;
            r >>= 1;
        }
        R::fold(&x, &y)
    }
}
//---------- end SegmentTree Point update Range query ----------
//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 より
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let 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, bytes) => {
        read_value!($iter, String).bytes().collect::<Vec<u8>>()
    };
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

//

// C -> AB -> AAC -> AAAB -> B
// C -> B としていい
//
// A -> BB
// B -> AB
// AAA -> empty
//
// 右端のAのmod 3?
// 両方操作可能ならそうかも知れんが片方だけしか動かせない
//
// B -> AB -> AAB -> AAAB -> B
// 操作可能な方は操作続けることで
// B...BA..A みたいにできる
// Bの数がT以下かつmod2で等しいかつ右端のAの数が一致
// いや右端のAを操作してBにすること考えると？
// 差分/2の分だけBに変換する余裕あり
// AAA -> empty もある
//
// WA
//
// Bがない場合とか
//
// WA
//
//
//

struct R;
impl PURQ for R {
    // B...BA...A
    // でBの数、Aの数
    type T = (usize, usize);
    fn fold(l: &Self::T, r: &Self::T) -> Self::T {
        if r.0 == 0 {
            (l.0, l.1 + r.1)
        } else {
            (l.0 + r.0, r.1)
        }
    }
    fn e() -> Self::T {
        (0, 0)
    }
}

fn run() {
    input! {
        s: bytes,
        t: bytes,
        q: usize,
        ask: [(usize1, usize, usize1, usize); q],
    }
    let mut seg_s = SegmentTreePURQ::<R>::new(s.len());
    for (i, s) in s.iter().enumerate() {
        if *s == b'A' {
            seg_s.update_tmp(i, (0, 1));
        } else {
            seg_s.update_tmp(i, (1, 0));
        }
    }
    seg_s.update_all();
    let mut seg_t = SegmentTreePURQ::<R>::new(t.len());
    for (i, s) in t.iter().enumerate() {
        if *s == b'A' {
            seg_t.update_tmp(i, (0, 1));
        } else {
            seg_t.update_tmp(i, (1, 0));
        }
    }
    seg_t.update_all();
    let mut out = String::new();
    for (a, b, c, d) in ask {
        let ans = || -> bool {
            let (x, y) = seg_s.find(a, b);
            let (z, w) = seg_t.find(c, d);
            let mut ans = false;
            if x == 0 {
                if z > 0 {
                    ans |= y > w && z % 2 == 0;
                } else {
                    ans |= (y - w) % 3 == 0;
                }
                return ans;
            }
            if z >= x && (z - x) % 2 == 0 && y >= w {
                let d = (z - x) / 2;
                let mut ok = false;
                ok |= (y - w) % 3 == 0;
                ok |= d > 0 && y > w;
                ans |= ok;
            }
            ans
        }();
        if ans {
            out.push('1');
        } else {
            out.push('0');
        }
    }
    println!("{}", out);
}

fn main() {
    run();
}


// ---------- begin input macro ----------
// reference: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let 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, bytes) => {
        read_value!($iter, String).bytes().collect::<Vec<u8>>()
    };
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}
// ---------- end input macro ----------

// 長さ3までしかなさそう
// 1~3までをそれぞれ数えられればいい
// 長さ1
// gcd > 1 なペアの数
// 長さ2
// gcd = 1 で最小素因数の積がN 以下なもの
// 長さ3
// 最小素因数の積がNを超えるやつ
// どう数える
// 1
// 包除原理でいけるはず
// 2, 3
// 最小素因数で分類すればなんとかなる?
// 2 * p > N な素数は削除しておく
// 互いに素の条件を扱えてなかった...
// 最小素因数の積がNを超えてるなら互いに素になる
// 超えないなら？
// 事前にメモっておけばいい感じか?
// ややこしい
// 最小素因数が異なるかつ積がN以下かつ互いに素じゃないペアの数
//

fn run() {
    input! {
        n: usize,
    }
    let mut factor = (0..=n).collect::<Vec<_>>();
    let mut mobius = vec![1i8; n + 1];
    let mut sub = 0;
    let mut prime = vec![];
    let mut cnt = vec![];
    for i in 2..=n {
        if i == factor[i] {
            prime.push(i);
            let mut c = 0;
            let mut d = 0;
            for j in 1..=(n / i) {
                let p = &mut factor[j * i];
                if i <= *p {
                    *p = i;
                    c += 1;
                } else {
                    d += 1;
                }
                mobius[j * i] *= -1;
            }
            sub += c * d;
            cnt.push(c);
            let pp = i.saturating_mul(i);
            for j in 1..=(n / pp) {
                mobius[j * pp] = 0;
            }
        }
    }
    let mut ans = 0i64;
    for (i, mobius) in mobius.iter().enumerate().skip(2) {
        let s = *mobius as i64;
        if s != 0 {
            let cnt = (n / i) as i64;
            ans -= cnt * (cnt - 1) / 2 * s;
        }
    }
    while prime.last().map_or(false, |p| 2 * *p > n) {
        prime.pop();
        cnt.pop();
    }
    /*
    for (i, (a, x)) in cnt.iter().zip(prime.iter()).enumerate() {
        for (b, y) in cnt.iter().zip(prime.iter()).take(i) {
            if *x * *y <= n {
                ans += 2 * *a * *b;
            } else {
                ans += 3 * *a * *b;
            }
        }
    }
    */
    ans -= 2 * sub;
    let mut sum = 0;
    let mut x = 0;
    let mut two = 0;
    for (i, (c, p)) in cnt.iter().zip(prime.iter()).enumerate() {
        while x < i && *p * prime[x] <= n {
            two += cnt[x];
            x += 1;
        }
        while x > 0 && *p * prime[x - 1] > n {
            x -= 1;
            two -= cnt[x];
        }
        ans += two * *c * 2 + (sum - two) * *c * 3;
        sum += *c;
    }
    println!("{}", ans);
}

fn main() {
    run();
}


use std::io::{stdin, BufRead, Stdin, StdinLock};

fn regular_sequence_exist(num_ll: usize, _num_lr: usize, num_rl: usize, num_rr: usize) -> bool {
    return (num_rl <= 2 * num_ll) && (num_rl <= 2 * num_rr);
}

#[cfg(test)]
mod test
{
    use super::regular_sequence_exist;

    #[test]
    fn test1() {
        let (num_ll, num_lr, num_rl, num_rr): (usize, usize, usize, usize) = (3, 1, 4, 3);
        let result: bool = regular_sequence_exist(num_ll, num_lr, num_rl, num_rr);
        assert_eq!(result, true);
    }
    #[test]
    fn test2() {
        let (num_ll, num_lr, num_rl, num_rr): (usize, usize, usize, usize) = (0, 0, 0, 0);
        let result: bool = regular_sequence_exist(num_ll, num_lr, num_rl, num_rr);
        assert_eq!(result, true);
    }
    #[test]
    fn test3() {
        let (num_ll, num_lr, num_rl, num_rr): (usize, usize, usize, usize) = (1, 2, 3, 4);
        let result: bool = regular_sequence_exist(num_ll, num_lr, num_rl, num_rr);
        assert_eq!(result, false);
    }
}

fn read_data() -> (usize, usize, usize, usize) {
    let stdin_stream: Stdin = stdin();
    let mut stdin_handle: StdinLock = stdin_stream.lock();

    let mut data: Vec<usize> = Vec::with_capacity(4);

    for _ in 0..4 {
        let mut value_str: String = String::new();
        stdin_handle.read_line(&mut value_str).unwrap();
        data.push(value_str.trim().parse::<usize>().unwrap());
    }

    return (data[0], data[1], data[2], data[3]);
}

fn main() {
    let (num_ll, num_lr, num_rl, num_rr): (usize, usize, usize, usize) = read_data();

    if regular_sequence_exist(num_ll, num_lr, num_rl, num_rr) {
        println!("1");
    } else {
        println!("0");
    }
}


#[allow(unused_imports)]
use std::cmp::{max, min, Ordering};
#[allow(unused_imports)]
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};
#[allow(unused_imports)]
use std::io::prelude::BufRead;
#[allow(unused_imports)]
use std::io::{stdin, stdout, BufReader, BufWriter, Write};
#[allow(unused_imports)]
use std::mem::swap;
#[allow(unused_imports)]
use std::str::FromStr;

fn main() {
    let a = read::<u64>();
    let b = read::<u64>();
    let c = read::<u64>();
    let d = read::<u64>();

    if (c == 0 || (c > 0 && a > 0 && b > 0)) && (2 * a + c) == (2 * d + c) {
        println!("1");
    } else {
        println!("0");
    }
}

#[allow(dead_code)]
fn read<T>() -> T
where
    T: std::str::FromStr,
    T::Err: std::fmt::Debug,
{
    let mut buf = String::new();
    stdin().read_line(&mut buf).unwrap();
    return buf.trim().parse().unwrap();
}

#[allow(dead_code)]
fn read_vector<T>() -> Vec<T>
where
    T: std::str::FromStr,
    T::Err: std::fmt::Debug,
{
    let mut buf = String::with_capacity(100);
    stdin().read_line(&mut buf).unwrap();
    return buf.split_whitespace().map(|s| s.parse().unwrap()).collect();
}

#[allow(dead_code)]
fn read_matrix<T>() -> Vec<Vec<T>>
where
    T: std::str::FromStr,
    T::Err: std::fmt::Debug,
{
    use std::io::prelude::*;
    let stdin = stdin();
    let mut reader = BufReader::with_capacity(100 * 1024, stdin);
    let mut line = String::with_capacity(100);
    let mut matrix: Vec<Vec<T>> = Vec::new();

    while reader.read_line(&mut line).unwrap() > 0 {
        matrix.push(
            line.trim()
                .split_whitespace()
                .map(|s| s.parse().unwrap())
                .collect(),
        );
        line.clear();
    }

    return matrix;
}

#[allow(dead_code)]
fn read_chars() -> Vec<char> {
    let stdin = stdin();
    let mut buf = String::new();
    let _bytes = stdin.read_line(&mut buf).unwrap();
    return buf.trim().chars().collect();
}


use std::io;

fn main() -> io::Result<()> {
    let mut input = String::new();

    let mut v: Vec<usize> = vec![];

    for _i in 0..4 {
        io::stdin().read_line(&mut input)?;
        v.push(input.trim().parse::<usize>().unwrap());
        input.clear();
    }

    let mut result = 1;
    if v[0] != v[3] {
        result = 0;
    }

    println!("{}", result);

    Ok(())
}


#![allow(unused_imports)]
use std::cmp::Ordering::*;
use std::io::{self, BufWriter, Write};
use std::str::{self, SplitAsciiWhitespace};
use std::collections::{BTreeSet, BTreeMap};

// I have no idea what I'm doing

const M: i64 = 1_000_000_007;

fn fexp(mut x: i64, mut e: i64) -> i64 {
    let mut ans = 1;
    while e > 0 {
        if e & 1 != 0 {
            ans = ans * x % M;
        }

        x = x * x % M;

        e >>= 1;
    }
    ans
}

struct DSU {
    p: Vec<usize>,
    s: Vec<usize>,
}

impl DSU {
    fn new(n: usize) -> Self {
        Self {
            p: (0..n).collect(),
            s: vec![1; n],
        }
    }

    fn find(&mut self, mut i: usize) -> usize {
        while i != self.p[i] {
            self.p[i] = self.p[self.p[i]];
            i = self.p[i];
        }
        i
    }

    fn union(&mut self, mut i: usize, mut j: usize) -> usize {
        i = self.find(i);
        j = self.find(j);
        if i == j { return i; }
        let (i, j) = if self.s[i] < self.s[j] { (i, j) } else { (j, i) };
        self.p[i] = j;
        self.s[j] += self.s[j];
        j
    }

    fn classes(&self) -> usize {
        self.p.iter().collect::<BTreeSet<_>>().len()
    }
}

fn main() -> Result<(), io::Error> {
    let (stdin, stdout) = (io::stdin(), io::stdout());
    let mut scan = UnsafeScanner::new(stdin.lock());
    let mut out = BufWriter::new(stdout.lock());

    let p: usize = scan.token();
    let k: i64 = scan.token();

    let mut dsu = DSU::new(p);

    for x in 0..p {
        dsu.union(x, ((k * x as i64) % p as i64) as usize);
    }

    writeln!(out, "{}", fexp(p as i64, (dsu.classes() - 1) as i64))?;

    Ok(())
}

///////////////////////////////////////////////////////////////////////////////////////////////////

/// Copied from https://github.com/EbTech/rust-algorithms/blob/master/src/scanner.rs
/// Same API as Scanner but nearly twice as fast, using horribly unsafe dark arts
/// **REQUIRES** Rust 1.34 or higher
pub struct UnsafeScanner<R> {
    reader: R,
    buf_str: Vec<u8>,
    buf_iter: SplitAsciiWhitespace<'static>,
}

impl<R: io::BufRead> UnsafeScanner<R> {
    pub fn new(reader: R) -> Self {
        Self {
            reader,
            buf_str: vec![],
            buf_iter: "".split_ascii_whitespace(),
        }
    }

    /// This function should be marked unsafe, but noone has time for that in a
    /// programming contest. Use at your own risk!
    pub fn token<T: str::FromStr>(&mut self) -> T {
        loop {
            if let Some(token) = self.buf_iter.next() {
                return token.parse().ok().expect("Failed parse");
            }
            self.buf_str.clear();
            self.reader
                .read_until(b'\n', &mut self.buf_str)
                .expect("Failed read");
            self.buf_iter = unsafe {
                let slice = str::from_utf8_unchecked(&self.buf_str);
                std::mem::transmute(slice.split_ascii_whitespace())
            }
        }
    }

    pub fn pair<T: str::FromStr>(&mut self) -> (T, T) {
        (self.token(), self.token())
    }
}


// ---------- begin ModInt ----------
mod modint {

    #[allow(dead_code)]
    pub struct Mod;
    impl ConstantModulo for Mod {
        const MOD: u32 = 1_000_000_007;
    }

    #[allow(dead_code)]
    pub struct StaticMod;
    static mut STATIC_MOD: u32 = 0;
    impl Modulo for StaticMod {
        fn modulo() -> u32 {
            unsafe { STATIC_MOD }
        }
    }

    #[allow(dead_code)]
    impl StaticMod {
        pub fn set_modulo(p: u32) {
            unsafe {
                STATIC_MOD = p;
            }
        }
    }

    use std::marker::*;
    use std::ops::*;

    pub trait Modulo {
        fn modulo() -> u32;
    }

    pub trait ConstantModulo {
        const MOD: u32;
    }

    impl<T> Modulo for T
    where
        T: ConstantModulo,
    {
        fn modulo() -> u32 {
            T::MOD
        }
    }

    pub struct ModInt<T>(pub u32, PhantomData<T>);

    impl<T> Clone for ModInt<T> {
        fn clone(&self) -> Self {
            ModInt::new_unchecked(self.0)
        }
    }

    impl<T> Copy for ModInt<T> {}

    impl<T: Modulo> Add for ModInt<T> {
        type Output = ModInt<T>;
        fn add(self, rhs: Self) -> Self::Output {
            let mut d = self.0 + rhs.0;
            if d >= T::modulo() {
                d -= T::modulo();
            }
            ModInt::new_unchecked(d)
        }
    }

    impl<T: Modulo> AddAssign for ModInt<T> {
        fn add_assign(&mut self, rhs: Self) {
            *self = *self + rhs;
        }
    }

    impl<T: Modulo> Sub for ModInt<T> {
        type Output = ModInt<T>;
        fn sub(self, rhs: Self) -> Self::Output {
            let mut d = T::modulo() + self.0 - rhs.0;
            if d >= T::modulo() {
                d -= T::modulo();
            }
            ModInt::new_unchecked(d)
        }
    }

    impl<T: Modulo> SubAssign for ModInt<T> {
        fn sub_assign(&mut self, rhs: Self) {
            *self = *self - rhs;
        }
    }

    impl<T: Modulo> Mul for ModInt<T> {
        type Output = ModInt<T>;
        fn mul(self, rhs: Self) -> Self::Output {
            let v = self.0 as u64 * rhs.0 as u64 % T::modulo() as u64;
            ModInt::new_unchecked(v as u32)
        }
    }

    impl<T: Modulo> MulAssign for ModInt<T> {
        fn mul_assign(&mut self, rhs: Self) {
            *self = *self * rhs;
        }
    }

    impl<T: Modulo> Neg for ModInt<T> {
        type Output = ModInt<T>;
        fn neg(self) -> Self::Output {
            if self.0 == 0 {
                Self::zero()
            } else {
                Self::new_unchecked(T::modulo() - self.0)
            }
        }
    }

    impl<T> std::fmt::Display for ModInt<T> {
        fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::fmt::Result {
            write!(f, "{}", self.0)
        }
    }

    impl<T: Modulo> std::str::FromStr for ModInt<T> {
        type Err = std::num::ParseIntError;
        fn from_str(s: &str) -> Result<Self, Self::Err> {
            let val = s.parse::<u32>()?;
            Ok(ModInt::new(val))
        }
    }

    impl<T: Modulo> From<usize> for ModInt<T> {
        fn from(val: usize) -> ModInt<T> {
            ModInt::new_unchecked((val % T::modulo() as usize) as u32)
        }
    }

    impl<T: Modulo> From<u64> for ModInt<T> {
        fn from(val: u64) -> ModInt<T> {
            ModInt::new_unchecked((val % T::modulo() as u64) as u32)
        }
    }

    impl<T: Modulo> From<i64> for ModInt<T> {
        fn from(val: i64) -> ModInt<T> {
            let m = T::modulo() as i64;
            ModInt::new((val % m + m) as u32)
        }
    }

    #[allow(dead_code)]
    impl<T> ModInt<T> {
        pub fn new_unchecked(d: u32) -> Self {
            ModInt(d, PhantomData)
        }
        pub fn zero() -> Self {
            ModInt::new_unchecked(0)
        }
        pub fn one() -> Self {
            ModInt::new_unchecked(1)
        }
        pub fn is_zero(&self) -> bool {
            self.0 == 0
        }
    }

    #[allow(dead_code)]
    impl<T: Modulo> ModInt<T> {
        pub fn new(d: u32) -> Self {
            ModInt::new_unchecked(d % T::modulo())
        }
        pub fn pow(&self, mut n: u64) -> Self {
            let mut t = Self::one();
            let mut s = *self;
            while n > 0 {
                if n & 1 == 1 {
                    t *= s;
                }
                s *= s;
                n >>= 1;
            }
            t
        }
        pub fn inv(&self) -> Self {
            assert!(self.0 != 0);
            self.pow(T::modulo() as u64 - 2)
        }
    }

    #[allow(dead_code)]
    pub fn mod_pow(r: u64, mut n: u64, m: u64) -> u64 {
        let mut t = 1 % m;
        let mut s = r % m;
        while n > 0 {
            if n & 1 == 1 {
                t = t * s % m;
            }
            s = s * s % m;
            n >>= 1;
        }
        t
    }
}
// ---------- end ModInt ----------
// ---------- begin Precalc ----------
mod precalc {
    use super::modint::*;
    #[allow(dead_code)]
    pub struct Precalc<T> {
        inv: Vec<ModInt<T>>,
        fact: Vec<ModInt<T>>,
        ifact: Vec<ModInt<T>>,
    }
    #[allow(dead_code)]
    impl<T: Modulo> Precalc<T> {
        pub fn new(n: usize) -> Precalc<T> {
            let mut inv = vec![ModInt::one(); n + 1];
            let mut fact = vec![ModInt::one(); n + 1];
            let mut ifact = vec![ModInt::one(); n + 1];
            for i in 2..(n + 1) {
                fact[i] = fact[i - 1] * ModInt::new_unchecked(i as u32);
            }
            ifact[n] = fact[n].inv();
            if n > 0 {
                inv[n] = ifact[n] * fact[n - 1];
            }
            for i in (1..n).rev() {
                ifact[i] = ifact[i + 1] * ModInt::new_unchecked((i + 1) as u32);
                inv[i] = ifact[i] * fact[i - 1];
            }
            Precalc {
                inv: inv,
                fact: fact,
                ifact: ifact,
            }
        }
        pub fn inv(&self, n: usize) -> ModInt<T> {
            assert!(n > 0);
            self.inv[n]
        }
        pub fn fact(&self, n: usize) -> ModInt<T> {
            self.fact[n]
        }
        pub fn ifact(&self, n: usize) -> ModInt<T> {
            self.ifact[n]
        }
        pub fn perm(&self, n: usize, k: usize) -> ModInt<T> {
            if k > n {
                return ModInt::zero();
            }
            self.fact[n] * self.ifact[n - k]
        }
        pub fn comb(&self, n: usize, k: usize) -> ModInt<T> {
            if k > n {
                return ModInt::zero();
            }
            self.fact[n] * self.ifact[k] * self.ifact[n - k]
        }
    }
}
// ---------- end Precalc ----------
//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 より
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let 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, bytes) => {
        read_value!($iter, String).bytes().collect::<Vec<u8>>()
    };
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

//

use modint::*;
use precalc::*;

type M = ModInt<Mod>;

fn run() {
    input! {
        p: u64,
        k: u64,
    }
    let ans = if k == 0 {
        M::from(p).pow(p - 1)
    } else {
        let mut phi = p - 1;
        let mut m = phi;
        for d in 2.. {
            if d * d > m {
                break;
            }
            if m % d == 0 {
                while m % d == 0 {
                    m /= d;
                }
                while phi % d == 0 && mod_pow(k, phi / d, p) == 1 {
                    phi /= d;
                }
            }
        }
        if m > 1 && mod_pow(k, phi / m, p) == 1 {
            phi /= m;
        }
        M::from(p).pow((p - 1) / phi)
    };
    println!("{}", ans);
}

fn main() {
    run();
}


use std::io;

fn zeros_fac(n : u32) -> u32 {
    let mut i = 5;
    let mut count = 0;
    while i <= n {
        count += n / i;
        i *= 5;
    }
    count
}

fn bsearch(mut pi : u32, mut pf : u32, n : u32) -> Option<u32> {
    while pf >= pi {
        let pm = (pf + pi) / 2;
        let zeros_pm = zeros_fac(5 * pm);
        if zeros_pm < n {
            pi = pm + 1;
        } else if zeros_pm == n {
            return Some(5 * pm);
        } else {
            pf = pm - 1;
        }
    }
    return None;
}

fn main() {
    let mut buffer = String::new();
    io::stdin().read_line(&mut buffer).expect("failed to read input");
    let n: u32 = buffer.trim().parse().expect("invalid input");

    match bsearch(4 * n / 5, n, n) {
        Some(x) => println!("{} {} {} {} {}", x, x + 1, x + 2, x + 3, x + 4),
        None => println!("0"),
    };
}


use std::io;

fn sum_digits(n : u16) -> u16 {
    let mut num = n;
    let mut sum = 0;
    while num != 0 {
        sum += num % 10;
        num /= 10;
    }
    sum
}

fn main() {
    let mut input = String::new();
    io::stdin().read_line(&mut input).expect("failed to read input");

    let mut n: u16 = input.trim().parse().expect("invalid input");
    let mut s = sum_digits(n) % 4;
    if n % 10 + s >= 10 {
        n = n + 10 - (n % 10);
        s = sum_digits(n) % 4;
    }
    println!("{}", n + if s != 0 { 4 - s } else { 0 });
}


#[allow(unused_imports)]
use std::io::{stdin, Read, StdinLock};
#[allow(unused_imports)]
use std::cmp::{max, min, Ordering};
#[allow(unused_imports)]
use std::str::FromStr;
#[allow(unused_imports)]
use std::collections::{HashSet, HashMap, BinaryHeap, VecDeque};
#[allow(unused_imports)]
use std::vec::Vec;

#[allow(dead_code)]
const INF: i32 = 1000_000_000;
#[allow(dead_code)]
const INFLL: i64 = 1000_000_000_000_000_000;
#[allow(dead_code)]
const EPS: f64 = 1.0e-10;
#[allow(dead_code)]
const MOD: i32 = 1000_000_007;
#[allow(dead_code)]
const MODLL: i64 = 1000_000_007;

struct Scanner<'a> {
    cin: StdinLock<'a>,
}

#[allow(dead_code)]
impl<'a> Scanner<'a> {
    fn new(cin: StdinLock<'a>) -> Scanner<'a> {
        Scanner {cin: cin}
    }
    fn read1<T: FromStr>(&mut self) -> Option<T> {
        let token = self.cin.by_ref().bytes().map(|c| c.unwrap() as char)
                    .skip_while(|c| c.is_whitespace())
                    .take_while(|c| !c.is_whitespace())
                    .collect::<String>();
        token.parse::<T>().ok()
    }
    fn read<T: FromStr>(&mut self) -> T {
        self.read1().unwrap()
    }
}

fn main() {
    let cin = stdin();
    let cin = cin.lock();
    let mut sc = Scanner::new(cin);

    let _n: usize = sc.read();
    let s: String = sc.read();
    let s: Vec<char> = s.chars().collect();

    fn vowel(c: char) -> bool {
        return c == 'a' || c == 'i' || c == 'e' || c == 'o' || c == 'u';
    }

    let mut ans: String = String::new();
    let mut last = '0';
    for c in s {
        if ans.len() == 0 {
            ans.push(c);
            last = c;
        } else {
            if vowel(last) && vowel(c) {
                continue;
            }
            ans.push(c);
            last = c;
        }
    }
    println!("{}", ans);
}


use std::io::stdin;
fn main(){
    let mut s:String=String::new();
    stdin().read_line(&mut s).unwrap();
    s.clear();
    stdin().read_line(&mut s).unwrap();
    s.trim();
    let b="aeyuio";
    let mut c:usize=1;
    let mut p:i32=0;
    let mut l:i32=0;
    while c<s.len(){
        match s.chars().nth(c).unwrap(){
            'a'=>p=1,
            'e'=>p=1,
            'y'=>p=1,
            'u'=>p=1,
            'i'=>p=1,
            'o'=>p=1,
            _=>p=0,
        }
        match s.chars().nth(c-1).unwrap(){
            'a'=>l=1,
            'e'=>l=1,
            'y'=>l=1,
            'u'=>l=1,
            'i'=>l=1,
            'o'=>l=1,
            _=>l=0,
        }
        if p==l{
            s.remove(c);
        }
        else{c+=1;}
    }
    println!("{}",s);
}


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

#[allow(unused_macros)]
macro_rules! readln {
    () => {{
        use std::io;

        let mut buf = String::new();
        io::stdin().read_line(&mut buf).unwrap();
        buf.trim().to_string()
    }};
    ( $t:ty ) => {{
        let input = readln!();
        input.parse::<$t>().unwrap()
    }};
    ( $( $t:ty ),+ ) => {{
        let input = readln!();
        let mut input = input.split_whitespace();
        (
            $(
                input.next().unwrap().parse::<$t>().unwrap(),
            )+
        )
    }}
}

#[allow(unused_macros)]
macro_rules! readvec {
    ( $t:ty ) => {{
        let input = readln!();
        let mut input = input.split_whitespace();
        let mut result = Vec::new();
        for elem in input {
            result.push(elem.parse::<$t>().unwrap());
        }
        result
    }}
}

fn main() {
    let (mut a, mut b) = readln!(i32,i32);
    let mut res = 0;
    while a>0 && b>0 {
        res += 1;
        if a >= b {
            a = max(0,a-2);
            b = min(100,b+1);
        } else {
            a = min(100,a+1);
            b = max(0,b-2);
        }
    }
    println!("{}",res);
}


struct Scan {
    buffer: std::collections::VecDeque<String>,
}

impl Scan {
    fn new() -> Scan {
        Scan {
            buffer: std::collections::VecDeque::new(),
        }
    }

    fn next<T: std::str::FromStr>(&mut self) -> T {
        loop {
            if let Some(token) = self.buffer.pop_front() {
                break token.parse::<T>().ok().unwrap();
            }
            let mut line = String::new();
            std::io::stdin().read_line(&mut line).expect("Fail to read");
            self.buffer = line.split_whitespace().map(String::from).collect();
        }
    }
}

fn _main() {
    let mut scan = Scan::new();
    let mut a1: usize = scan.next();
    let mut a2: usize = scan.next();
    let mut result = 0usize;
    while a1 > 0 && a2 > 0 {
        if a1 < a2 {
            a1 += 1;
            a2 -= 2;
        } else {
            a2 += 1;
            a1 -= 2;
        }
        result += 1;
    }
    println!("{}", result);
}

fn main() {
    std::thread::Builder::new()
        .stack_size(1 << 23)
        .spawn(_main)
        .unwrap()
        .join()
        .unwrap();
}


struct Scan {
    buffer: std::collections::VecDeque<String>,
}

impl Scan {
    fn new() -> Scan {
        Scan {
            buffer: std::collections::VecDeque::new(),
        }
    }

    fn next<T: std::str::FromStr>(&mut self) -> T {
        loop {
            if let Some(token) = self.buffer.pop_front() {
                break token.parse::<T>().ok().unwrap();
            }
            let mut line = String::new();
            std::io::stdin().read_line(&mut line).expect("Fail to read");
            self.buffer = line.split_whitespace().map(String::from).collect();
        }
    }
}

fn minval(a1: usize, a2: usize, depth: usize, table: &mut [[usize; 128]; 128]) -> usize {
    if a1 == 0 || a2 == 0 {
        return depth;
    }
    if table[a1][a2] != 0 {
        return table[a1][a2];
    }
    let mut result = 0usize;
    if a1 >= 2 {
        let val = {
            let a1 = a1 - 2;
            let a2 = a2 + 1;
            minval(a1.max(a2), a1.min(a2), depth + 1, table)
        };
        result = result.max(val);
    }
    if a2 >= 2 {
        let val = {
            let a1 = a1 + 1;
            let a2 = a2 - 2;
            minval(a1.max(a2), a1.min(a2), depth + 1, table)
        };
        result = result.max(val);
    }
    table[a1][a2] = result;
    result
}

fn _main() {
    let mut table = [[0; 128]; 128];
    let mut scan = Scan::new();
    let a1: usize = scan.next();
    let a2: usize = scan.next();
    let result = minval(a1, a2, 0, &mut table);
    println!("{}", result);
}

fn main() {
    std::thread::Builder::new()
        .stack_size(1 << 23)
        .spawn(_main)
        .unwrap()
        .join()
        .unwrap();
}


struct Scan {
    buffer: std::collections::VecDeque<String>,
}

impl Scan {
    fn new() -> Scan {
        Scan {
            buffer: std::collections::VecDeque::new(),
        }
    }

    fn next<T: std::str::FromStr>(&mut self) -> T {
        loop {
            if let Some(token) = self.buffer.pop_front() {
                break token.parse::<T>().ok().unwrap();
            }
            let mut line = String::new();
            std::io::stdin().read_line(&mut line).expect("Fail to read");
            self.buffer = line.split_whitespace().map(String::from).collect();
        }
    }
}

fn minval(a1: usize, a2: usize, depth: usize, table: &mut [[usize; 256]; 256]) -> usize {
    if a1 == 0 || a2 == 0 {
        return depth;
    }
    if table[a1][a2] != 0 {
        return table[a1][a2];
    }
    let mut result = 0usize;
    if a2 >= 2 {
        let val = {
            let a1 = a1 + 1;
            let a2 = a2 - 2;
            minval(a1.max(a2), a1.min(a2), depth + 1, table)
        };
        result = result.max(val);
    }
    if a1 >= 2 {
        let val = {
            let a1 = a1 - 2;
            let a2 = a2 + 1;
            minval(a1.max(a2), a1.min(a2), depth + 1, table)
        };
        result = result.max(val);
    }
    table[a1][a2] = result;
    result
}

fn _main() {
    let mut table = [[0; 256]; 256];
    let mut scan = Scan::new();
    let a1: usize = scan.next();
    let a2: usize = scan.next();
    let result = minval(a1.max(a2), a2.min(a2), 0, &mut table);
    println!("{}", result);
}

fn main() {
    std::thread::Builder::new()
        .stack_size(1 << 23)
        .spawn(_main)
        .unwrap()
        .join()
        .unwrap();
}


struct Scan {
    buffer: std::collections::VecDeque<String>,
}

impl Scan {
    fn new() -> Scan {
        Scan {
            buffer: std::collections::VecDeque::new(),
        }
    }

    fn next<T: std::str::FromStr>(&mut self) -> T {
        loop {
            if let Some(token) = self.buffer.pop_front() {
                break token.parse::<T>().ok().unwrap();
            }
            let mut line = String::new();
            std::io::stdin().read_line(&mut line).expect("Fail to read");
            self.buffer = line.split_whitespace().map(String::from).collect();
        }
    }
}

fn _main() {
    let mut scan = Scan::new();
    let n: usize = scan.next();
    let k: usize = scan.next();
    let d: usize = scan.next();
    let mut table = [[0usize; 2]; 128];
    table[0][1] = 1;
    for i in 1..=n {
        for j in 1..=k {
            if i >= j {
                table[i][0] = (table[i][0] + table[i - j][0]) % 1000000007;
                if j >= d {
                    table[i][0] = (table[i][0] + table[i - j][1]) % 1000000007;
                } else {
                    table[i][1] += (table[i][1] + table[i - j][1]) % 1000000007;
                }
            }
        }
    }
    println!("{}", table[n][0]);
}

fn main() {
    std::thread::Builder::new()
        .stack_size(1 << 23)
        .spawn(_main)
        .unwrap()
        .join()
        .unwrap();
}


use std::io;
use std::str;

pub struct Scanner<R> {
    reader: R,
    buffer: Vec<String>,
}

impl<R: io::BufRead> Scanner<R> {
    pub fn new(reader: R) -> Self {
        Self {
            reader,
            buffer: vec![],
        }
    }

    pub fn token<T: str::FromStr>(&mut self) -> T {
        loop {
            if let Some(token) = self.buffer.pop() {
                return token.parse().ok().expect("Failed parse");
            }
            let mut input = String::new();
            self.reader.read_line(&mut input).expect("Failed read");
            self.buffer = input.split_whitespace().rev().map(String::from).collect();
        }
    }
}

fn get_divisors(n: i64) -> Vec<i64> {
    let mut ans = vec![1, n];
    let mut d = 2;
    while d * d <= n {
        if n % d == 0 {
            ans.push(d);
            if d * d < n {
                ans.push(n / d);
            }
        }
        d += 1;
    }
    ans.sort();
    ans
}

fn kth_smallest_divisor(n: i64, k: i64) -> i64 {
    let k = k as usize;
    let divisors = get_divisors(n);
    if k >= divisors.len() {
        return -1;
    }
    divisors[k]
}

fn solve<R: io::BufRead, W: io::Write>(scan: &mut Scanner<R>, out: &mut W) {
    let n: i64 = scan.token();
    let k: i64 = scan.token();
    let ans = kth_smallest_divisor(n, k - 1);
    writeln!(out, "{}", ans).ok();
}

fn main() {
    let (stdin, stdout) = (io::stdin(), io::stdout());
    let mut scan = Scanner::new(stdin.lock());
    let mut out = io::BufWriter::new(stdout.lock());
    solve(&mut scan, &mut out);
}


macro_rules! read_line {
    ($v:ident) => {
        let mut temp = String::new();
        std::io::stdin().read_line(&mut temp).unwrap();
        let $v = temp;
    };
    (var, $t:ty, $($v:ident), *) => {
        read_line!(input_line);
        let mut iter = parse_token!($t, input_line);
        $(
            let $v = iter.next().unwrap();
        )*
    };
    (vec, $t:ty, $v:ident) => {
        read_line!(input_line);
        let iter = parse_token!($t, input_line);
        let $v: Vec<$t> = iter.collect();
    };
    ($($v:ident; $t:ty), *) => {
        read_line!(input_line);
        let mut iter = input_line.split_whitespace();
        $(
            let $v: $t = iter.next().unwrap().parse().unwrap();
        )*
    };
}

macro_rules! parse_token {
    ($t:ty, $e:expr) => {
        $e.split_whitespace().map(|x| x.parse::<$t>().unwrap());
    };
}

fn main() {
    read_line!(k;u64, n;u64);
    let mut cnt = 0;
    for i in 1..(k + 1) {
        if k % i == 0 {
            cnt += 1;
        }
        if cnt == n {
            println!("{}", i);
            return;
        }
    }

    println!("-1");
}


fn calculate_nth_divisor(n: i64, k: i64) -> Option<i64> {
    if k > n {
        return None;
    }

    let mut divisors = Vec::<i64>::with_capacity((k / 2) as usize);
    let max_small_divisor = (n as f64).sqrt().trunc() as i64;
    let mut count = k;

    for x in 1..=max_small_divisor {
        if n % x == 0 {
            count -= 1;
        }
        if count == 0 {
            return Some(x);
        } else {
            divisors.push(x);
        }
    }

    let size = divisors.len() as i64;
    let n_is_square = n == divisors.last().unwrap().pow(2);
    // dbg!(n, k, size, n_is_square, &divisors);
    if count > size || count == size && n_is_square {
        None
    } else {
        let mut idx = (size as i64 - count) as usize;
        if n_is_square {
            idx -= 1;
        }
        Some(n / divisors[idx])
    }
}

fn main() {
    let (n, k) = {
        let mut s = String::new();
        std::io::stdin().read_line(&mut s).unwrap();
        let mut iter = s.trim().split_ascii_whitespace();
        let n = iter.next().unwrap().parse::<i64>().unwrap();
        let k = iter.next().unwrap().parse::<i64>().unwrap();
        (n, k)
    };

    println!("{}", calculate_nth_divisor(n, k).unwrap_or(-1));
}


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

macro_rules! debug(
    ($($arg:tt)*) => { {
        let r = writeln!(&mut ::std::io::stderr(), $($arg)*);
        r.expect("failed printing to stderr");
    } }
);

struct Scanner {
   buffer : std::collections::VecDeque<String>
}

impl Scanner {

   fn new() -> Scanner {
      Scanner {
         buffer: std::collections::VecDeque::new()
      }
   }

   fn process(&mut self) -> String {
      if self.buffer.len() == 0 {
         let mut input = String::new();
         std::io::stdin().read_line(&mut input).ok();
         for word in input.split_whitespace() {
            self.buffer.push_back(word.to_string())
         }
      }

      self.buffer.pop_front().unwrap()
   }

   fn next<T : std::str::FromStr >(&mut self) -> T {
      self.process().parse::<T>().ok().unwrap()
   }

   #[allow(dead_code)]
   fn next_char(&mut self) -> char {
      self.process().into_bytes()[0] as char
   }
}

fn main() {
   let mut sin = Scanner::new();
   let (n, k) = (sin.next(), sin.next::<usize>());

   let mut factors = Vec::new();

   let mut i = 1;

   while i*i <= n {
      if n % i == 0 {
         factors.push(i);
      }
      i += 1;
   }

   let num_of_factors = 2*factors.len() - 1;

   if k < factors.len() {
      println!("{}", factors[k]);
   } else {
      if k > num_of_factors {
         println!("-1");
      } else {
         let mut index = k - factors.len();
         if (i-1)*(i-1) == n {
            index += 1;
         }
         println!("{}", n / factors[factors.len() - index]);
      }
   }
}


use std::io::{ self, BufRead };

macro_rules! scan_to_vec {
    ($count:expr, $t:ty) => ({
        let mut result = Vec::new();
        let stdin = io::stdin();
        let mut handle = stdin.lock();

        for _ in 0..$count {
            let mut buffer = String::new();
            handle.read_line(&mut buffer)
                .expect("scan_to_vec: failed at `handle.read_line`.");
            result.push(buffer.trim().parse::<$t>()
                .expect("scan_to_vec: failed at `parse::<$t>`."));
        }
        result
    })
}

macro_rules! scan_line_to_vec {
    ($t:ty) => ({
        let mut result = Vec::new();
        let stdin = io::stdin();
        let mut handle = stdin.lock();
        handle.read_line(&mut buffer)
            .expect("scan_line_to_vec: failed at `handle.read_line`.");

        for s in chunks.split_whitespace() {
            result.push(s.parse::<$t>()
                .expect("scan_line_to_vec: failed at `parse::<$t>`."));
        }
        result
    })
}

macro_rules! scan_line {
    () => ({
        let stdin = io::stdin();
        let mut handle = stdin.lock();
        let mut buffer = String::new();
        handle.read_line(&mut buffer)
            .expect("scan_line: failed at `handle.read_line`.");
        buffer
    });
    ( $($t:ty)+ ) => ({
        let stdin = io::stdin();
        let mut handle = stdin.lock();
        let mut buffer = String::new();
        handle.read_line(&mut buffer)
            .expect("scan_line: failed at `handle.read_line`.");
        let mut chunks = buffer.split_whitespace();

        ($(
            {
                chunks.next()
                    .expect("scan_line: failed at `next`, # of space separated strings not equal to requested #")
                .parse::<$t>()
                    .expect("scan_line: failed at `parse::<$t>`.")
            },
        )+)
    })
}

fn main() {
    let (n, k) = scan_line!(u64 usize);
    let mut factors = vec![];

    let mut i = 1;

    while i*i <= n {
        if n % i == 0 {
            factors.push(i);
        }
        i += 1;
    }

    for j in 0..factors.len() {
        let x = n / factors[j];
        factors.push(x);
    }
    factors.sort();

    if k - 1 >= factors.len() {
        println!("-1");
    } else {
        println!("{}", factors[k - 1]);
    }
}