process.stdin.resume();
process.stdin.setEncoding('utf8');

// 標準入力取込
let gInput = '';
process.stdin.on('data', (chunk) => (gInput += chunk));
process.stdin.on('end', () => main(gInput.split(/\r?\n/)));

// 解答
function main(inputs: string[]): void {
  const length = Number(inputs[0]);
  const str = inputs[1];
  let rejectCount = 0;
  let sum = 0;

  if (str.includes('R') && str.includes('G') && str.includes('B')) {
    sum += (str.split('R').length - 1) * (str.split('G').length - 1) * (str.split('B').length - 1);
  } else {
    console.log(sum);
    return;
  }

  for (let i = 0; i < length; i++) {
    for (let j = 1; j < length; j++) {
      if (i + j >= length || i + j * 2 >= length) {
        break;
      }

      if (str[i] !== str[i + j] && str[i] !== str[i + j * 2] && str[i + j] !== str[i + j * 2]) {
        rejectCount++;
      }
    }
  }

  sum -= rejectCount;

  console.log(sum);
}


process.stdin.resume();
process.stdin.setEncoding('utf8');

// 標準入力取込
let gInput = '';
process.stdin.on('data', (chunk) => (gInput += chunk));
process.stdin.on('end', () => main(gInput.split(/\r?\n/)));

// 解答
function main(inputs: string[]): void {
  const length = Number(inputs[0]);
  const str = inputs[1];
  const checkList = ['R', 'G', 'B'];
  let rejectCount = 0;
  let sum = 0;

  if (str.includes('R') && str.includes('G') && str.includes('B')) {
    sum += (str.split('R').length - 1) * (str.split('G').length - 1) * (str.split('B').length - 1);
  } else {
    console.log(sum);
    return;
  }

  for (let i = 0; i < length; i++) {
    for (let j = 1; j < length; j++) {
      if (i + j >= length || i + j * 2 >= length) {
        break;
      }

      if (str[i] !== str[i + j] && str[i] !== str[i + j * 2] && str[i + j] !== str[i + j * 2]) {
        rejectCount++;
      }
    }
  }

  sum -= rejectCount;

  console.log(sum);
}


import * as fs from 'fs'

const input: string = fs.readFileSync('/dev/stdin', 'utf8');
const args: string[][] = input.split('\n').map(l => l.split(' '));

const n: number = parseInt(args[0][0]);
const s: string = args[1][0];

let cnt = 0;
for (let i = 0; i < n - 2; i++) {
  for (let j = i + 1; j < n - 1; j++) {
    for (let k = j + 1; k < n; k++) {
      if (j - i !== k - j) {
        if (s[i] !== s[j] && s[j] !== s[k] && s[k] !== s[i]) cnt++;
      }
    }
  }
}

console.log(cnt);


import * as fs from "fs";

function main(lines: string[][]) {
  const data = lines[1][0].split("");
  let count = 0;
  data.forEach((n1, i1) => {
    data.forEach((n2, i2) => {
      if (i1 < i2) return;
      if (n1 === n2) return;
      data.forEach((n3, i3) => {
        if (i2 < i3) return;
        if (n2 === n3) return;
        if (n1 === n3) return;
        if (i3 - i2 === i2 - i1) return;
        count++;
      });
    });
  });
  console.log(count);
}

const lines = fs
  .readFileSync("/dev/stdin", "utf8")
  .split("\n")
  .map((l) => l.split(" "))
  .filter((input) => !(input.length === 1 && input[0] === ""));

main(lines);


import * as fs from 'fs';

function Main(input: string) {
    const lines = input.split('\n');
    const constraintN = parseInt(lines[0], 10);
    const S = lines[1];

    let sum = 0;

    let maxI = constraintN - 2;
    let maxJ = constraintN - 1;

    for (let i = 0; i < maxI; i++) {
        for (let j = i + 1; j < maxJ; j++) {
            for (let k = j + 1; k < constraintN; k++) {
                if (j - i !== k - j &&
                    S[i] !== S[j] &&
                    S[i] !== S[k] &&
                    S[j] !== S[k]) {
                    sum++;
                }
            }
        }
    }

    //output
    console.log(sum);
}

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


A, B, K = map(int, input().split())
a, b = [], []
for i in range(1,A+1):
    if A % i == 0:
        a.append(i)
for j in range(1,B+1):
    if B % j == 0:
        b.append(j)
lis = [k for k in a if k in b]
lis.reverse()
print(lis[K-1])


A, B, K = map(int, input().split())

for i in range(1, min(A, B) + 1)[::-1]:
    if A % i == 0 and B % i == 0:
        K -= 1

    if K == 0:
        print(i)
        break


a,b,k = map(int,input().split())
l = []
for i in range(1,101):
    if a%i == 0 and b%i == 0:
        l.append(i)
print(l[::-1][k-1])


import numpy as np
A,B,K = map(int,input().split())

def cal_common_divisor(num1,num2):
    prime = [2,3,5,7,11,13]
    ans_list = []
    for i in range(len(prime)):
        while True:
            if num1 % prime[i] == 0 and num2 % prime[i] == 0:
                num1 //= prime[i]
                num2 //= prime[i]
                ans_list.append(prime[i])
            if num1 % prime[i] != 0 or num2 % prime[i] != 0:
                break
    return ans_list

ans = cal_common_divisor(A,B)
n = len(ans)

nnn = []
for i in range(2**n):
    negt = []
    num = 1
    for j in range(n):
        if ((i >> j)& 1):
            negt.append(ans[j])
    for k in range(len(negt)):
        num *= negt[k]
    nnn.append(num)
nnn = list(set(nnn))
nnn.sort(reverse=True)
print(nnn[K-1])


import numpy as np
A,B,K = map(int,input().split())

def cal_common_divisor(num1,num2):
    prime = [2,3,5,7,11,13]
    ans_list = []
    for i in range(len(prime)):
        while True:
            if num1 % prime[i] == 0 and num2 % prime[i] == 0:
                num1 //= prime[i]
                num2 //= prime[i]
                ans_list.append(prime[i])
            if num1 % prime[i] != 0 or num2 % prime[i] != 0:
                break
    return ans_list

ans = cal_common_divisor(A,B)
n = len(ans)

nnn = []
for i in range(2**n):
    negt = []
    num = 1
    for j in range(n):
        if ((i >> j)& 1):
            negt.append(ans[j])
    for k in range(len(negt)):
        num *= negt[k]
    nnn.append(num)
nnn = list(set(nnn))
nnn.sort(reverse=True)
print(nnn)
print(nnn[K-1])


a,b,k = map(int,input().split())

num = 0
metric_num = 0

while True:
    num += 1
    if a % num ==0 and b % num ==0:
        metric_num += 1
        if metric_num == k:
            break
print(num)


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

public class Main {
  public static void main(String[] args) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String[] str = in.readLine().split(" ");
    int a = Integer.parseInt(str[0]);
    int b = Integer.parseInt(str[1]);
    int k = Integer.parseInt(str[2]);

    int[] divisor_array = new int[k];

    for(int i = Math.min(a,b), j = 0; i>=1; i--) {
      if(a%i==0 && b%i==0){
        divisor_array[j] = i;
        j++;
      }
      if(j == k)
        break;
    }
    System.out.println(divisor_array[k-1]);
  }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class Main{
	public static void main(String[] args){
		InputStreamReader ir = new InputStreamReader(System.in);
		BufferedReader br = new BufferedReader(ir);

		String str = null;
		try{
			str = br.readLine();
		}catch(IOException ex){
			ex.printStackTrace();
		}

		String[] input = str.split(" ");
		int a = Integer.parseInt(input[0]);
		int b = Integer.parseInt(input[1]);
		int k = Integer.parseInt(input[2]);

		List<Integer> res = new ArrayList<>();
		for(int i = 1; i <= 100; i++){
			if(a % i == 0 && b % i == 0){
				res.add(i);
			}
		}
		System.out.println(res.get(res.size() - k));
	}
}


import java.util.stream.IntStream;
import java.io.*;
import java.util.*;

public class Main {

    public static void main(String[] args) {
        FastScanner sc = new FastScanner();
        PrintWriter out = new PrintWriter(System.out);

        final int A = sc.nextInt();
        final int B = sc.nextInt();
        final int K = sc.nextInt();
        int cnt = 0;
        int ans = 0;

        for (int i = Math.max(A, B); i > 0; i--) {
            if (A % i == 0 && B % i == 0) cnt++;
            if (cnt == K) {
                ans = i;
                break;
            }
        }

        out.println(ans);

        out.flush();
    }
}

// https://qiita.com/p_shiki37/items/a0f6aac33bf60f5f65e4
class FastScanner {

    private final InputStream in = System.in;
    private final byte[] buffer = new byte[1024];
    private int ptr = 0;
    private int buflen = 0;

    private boolean hasNextByte() {
        if (ptr < buflen) {
            return true;
        } else {
            ptr = 0;
            try {
                buflen = in.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (buflen <= 0) {
                return false;
            }
        }
        return true;
    }

    private int readByte() {
        if (hasNextByte()) {
            return buffer[ptr++];
        } else {
            return -1;
        }
    }

    private static boolean isPrintableChar(int c) {
        return 33 <= c && c <= 126;
    }

    public boolean hasNext() {
        while (hasNextByte() && !isPrintableChar(buffer[ptr])) {
            ptr++;
        }
        return hasNextByte();
    }

    public String next() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }
        StringBuilder sb = new StringBuilder();
        int b = readByte();
        while (isPrintableChar(b)) {
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

    public long nextLong() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }
        long n = 0;
        boolean minus = false;
        int b = readByte();
        if (b == '-') {
            minus = true;
            b = readByte();
        }
        if (b < '0' || '9' < b) {
            throw new NumberFormatException();
        }
        while (true) {
            if ('0' <= b && b <= '9') {
                n *= 10;
                n += b - '0';
            } else if (b == -1 || !isPrintableChar(b)) {
                return minus ? -n : n;
            } else {
                throw new NumberFormatException();
            }
            b = readByte();
        }
    }

    public int nextInt() {
        long nl = nextLong();
        if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) {
            throw new NumberFormatException();
        }
        return (int) nl;
    }

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


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Main {

	public void run() throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String line = br.readLine();
		List<Integer> arrayData = new ArrayList<Integer>();
		String[] lineArray = line.split(" ");
		for (String token : lineArray) {
			arrayData.add(Integer.parseInt(token));
		}
		int A = arrayData.get(0);
		int B = arrayData.get(1);
		int K = arrayData.get(2);
		List<Integer> li = new ArrayList<Integer>();
		for(int i=1; i<=A;i++){

				if(A%i == 0 && B%i == 0){
					li.add(i);
				}

		}

		System.out.println(li.get(K-1));
	}
    public static void main(String[] args) throws Exception {
        new Main().run();
    }

}


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

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int b = sc.nextInt();
        int k = sc.nextInt();
        int num = 0;
        for (int i = 1; i < Math.max(a, b); i++) {
            if (a % i == 0 && b % i == 0)
                num++;
            if (num == k)
                System.out.println(i);
                if(num == k)
                    break;
        }
    }
}


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

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int b = sc.nextInt();
        int k = sc.nextInt();
        int num = 0;
        for (int i = 1; i < Math.max(a, b); i++) {
            if (a % i == 0 && b % 0 == 0)
                num++;
            if (num == k)
                System.out.println(i);
                if(num == k)
                    break;
        }
    }
}


#include <iostream>
#include <sstream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cctype>
#include <cstring>
#include <iomanip>
#include <bitset>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
#include <deque>
#include <set>
#include <list>
#include <map>

using namespace std;

int main() {
  int a, b, c;
  cin >> a >> b >> c;
  int cnt = 0;
  for (int i = a; i >= 1; i--) {
    if (a % i == 0 && b % i == 0) cnt++;
    if (cnt == c) {
      cout << i << endl;
      return 0;
    }
  }
  return 0;
}


#include <iostream>
#include <algorithm>
#include <cstdio>
#include <regex>
#include <cmath>
#include <vector>
#include <queue>
#include <functional>
#include <numeric>
#include <iomanip>
#include <stack>
#include <string>
#include <map>
#include <set>
using namespace std;

template <class T>
using V = vector<T>;
template <class T>
using VV = V<V<T>>;
template <class T>
using VVV = V<VV<T>>;
template <class T, class U>
using P = pair<T, U>;
template <class S, class T, class U>
using TUP = tuple<S, T, U>;

using ll = long long;
using ull = unsigned long long;
using dbl = double;
using str = string;
using vll = V<ll>;
using vll2 = VV<ll>;
using vll3 = VVV<ll>;
using pll = P<ll, ll>;
using tll = TUP<ll, ll, ll>;
using vpll = V<pll>;
using tpll = V<tll>;
using vs = V<str>;
using vvs = V<vs>;
using vd = V<dbl>;
using vvd = V<vd>;
using qll = queue<ll>;
using qpll = queue<pll>;
using mapll = map<ll, ll>;
using setll = set<ll>;

#define int ll
#define fst first
#define snd second
#define PQ priority_queue
#define mp make_pair
#define mt make_tuple
#define pb push_back
#define popb pop_back()
#define sz size()
#define bn begin()
#define ed end()
#define FOR(i, a, b) for (ll i = (a); i <= (ll)(b); i++)
#define rFOR(i, a, b) for (ll i = (b); i >= (ll)(a); i--)
#define REP(i, n) FOR(i, 0, (n)-1)
#define REP1(i, n) FOR(i, 1, (n))
#define VFOR(i, v) for (auto &(i) : v)
#define IOTA(a, n) \
	vll(a)((n));   \
	iota((a).bn, (a).ed, (0));
#define SORT_ASC(a) sort((a).bn, (a).ed)
#define SORT_DESC(a) sort((a).rbegin(), (a).rend())
#define UNIQUE(a) (a).erase(unique((a).bn, (a).ed), (a).ed)
#define PREVP(a) prev_permutation((a).bn, (a).ed)
#define NEXTP(a) next_permutation((a).bn, (a).ed)
#define BINS(a, target) binary_search((a).bn, (a).ed, target)
#define LB(a, target) lower_bound((a).bn, (a).ed, target)
#define FIND(a, target) find((a).bn, (a).ed, target)
#define UB(a, target) upper_bound((a).bn, (a).ed, target)
#define CNT(a, target) count((a).bn, (a).ed, target)
#define SUM(a) accumulate((a).bn, (a).ed, 0)
#define DEBUG(...)     \
	dal(#__VA_ARGS__); \
	dal(__VA_ARGS__)
#define Dig2(a, b) ((a) >> (b)&1)
#define Dig10(a, b) (ll)(((a) / ((ll)(pow(10.0, (dbl)(b))))) % 10)
#define DigN2(a) ((llabs(a) == 0) ? 1 : ((ll)log2((dbl)llabs(a)) + 1))
#define DigN10(a) ((llabs(a) == 0) ? 1 : ((ll)log10((dbl)llabs(a)) + 1))
#define Pow2(a) ((ll)(1) << (a))
#define Pow10(a) ((ll)(pow(10.0, double(a))))
#define LSB(a) ((a) & -(a))
#define llin(n) \
	ll n;       \
	cin >> n;
#define strin(n) \
	str n;       \
	cin >> n;
#define vin(v) \
	VFOR(i, v) { cin >> (i); };
#define vllin(v, N) \
	vll(v)((N));    \
	vin(v);
#define vl4in(v1, v2, N) \
	vll(v1)(N), (v2)(N); \
	REP(i, N) { cin >> (v1)[i] >> (v2)[i]; };
#define vl6in(v1, v2, v3, N)      \
	vll(v1)(N), (v2)(N), (v3)(N); \
	REP(i, N) { cin >> (v1)[i] >> (v2)[i] >> (v3)[i]; };
#define vsin(v, N) \
	vs(v)((N));    \
	vin(v);
#define min(...) Min(__VA_ARGS__)
#define max(...) Max(__VA_ARGS__)
#define emin(a, ...) ((a) = Min((a), __VA_ARGS__))
#define emax(a, ...) ((a) = Max((a), __VA_ARGS__))
#define egcd(a, ...) ((a) = gcd((a), __VA_ARGS__))
#define elcm(a, ...) ((a) = lcm((a), __VA_ARGS__))
#define tf(cond, t, f) if(cond){echo(t);}else{echo(f);}
#define yn(cond) tf(cond, "yes", "no")
#define Yn(cond) tf(cond, "Yes", "No")
#define YN(cond) tf(cond, "YES", "NO")

static const ll MOD = (ll)1e9 + 7;
static const ll INF = (1LL << 62) - 1; // 4.611E+18
static const dbl PI = acos(-1.0);

void Input(){};
template <class T, class... Args>
void Input(T &t, Args &... args)
{
	cin >> t;
	Input(args...);
}

void vInit(ll size) {}
template <class T, class... Args>
void vInit(ll size, V<T> &v, Args &... args)
{
	v.resize(size);
	vInit(size, args...);
}

void vInputNum(ll num) {}
template <class T, class... Args>
void vInputNum(ll num, V<T> &v, Args &... args)
{
	cin >> v[num];
	vInputNum(num, args...);
}

void vInput(ll size) {}
template <class... Args>
void vInput(ll size, Args &... args)
{
	vInit(size);
	REP(i, size)
	{
		vInputNum(i, args...);
	}
}

template <class S, class T>
ostream &operator<<(ostream &o, const P<S, T> &p)
{
	return o << "(" << p.first << ", " << p.second << ")";
}

template <class T>
ostream &operator<<(ostream &o, const V<T> &v)
{
	if (v.empty())
	{
		return o << "[]";
	}
	else
	{
		auto itr = v.bn;
		o << "[" << *itr;
		itr++;
		while (itr != v.ed)
		{
			o << ", " << *itr;
			itr++;
		}
		o << "]";
		return o;
	}
}

template <class T>
ostream &operator<<(ostream &o, queue<T> q)
{
	if (q.empty())
	{
		return o << "| |";
	}
	else
	{
		while (!q.empty())
		{
			o << "| " << q.front() << " ";
			q.pop();
		}
		o << "|";
		return o;
	}
}

template <class S, class T>
ostream &operator<<(ostream &o, const map<S, T> &m)
{
	if (m.empty())
	{
		return o << "[]";
	}
	else
	{
		auto itr = m.bn;
		o << "{" << itr->first << ": " << itr->second;
		itr++;
		while (itr != m.ed)
		{
			o << "} {" << itr->first << ": " << itr->second;
			itr++;
		}
		o << "}";
		return o;
	}
}

template <class T>
ostream &operator<<(ostream &o, const set<T> &s)
{
	if (s.empty())
	{
		return o << "<>";
	}
	else
	{
		auto itr = s.bn;
		o << "<" << *itr;
		itr++;
		while (itr != s.ed)
		{
			o << ", " << *itr;
			itr++;
		}
		o << ">";
		return o;
	}
}

void say() {}
template <class T>
void say(T t) { cout << t; }
template <class Head, class... Body>
void say(Head h, Body... b)
{
	cout << h;
	say(b...);
}
void echo() { cout << "\n"; }
template <class... Args>
void echo(Args... args)
{
	say(args...);
	cout << "\n";
}

void dbgsay() {}
template <class T>
void dbgsay(T t) { cout << t; }
template <class Head, class... Body>
void dbgsay(Head h, Body... b)
{
	cerr << h << " ";
	dbgsay(b...);
}
void dbgecho() { cout << "\n"; }
template <class... Args>
void dbgecho(Args... args)
{
	dbgsay(args...);
	cerr << "\n";
}

void echovv() {}
template <class T>
void echovv(VV<T> v)
{
	if (v.empty())
	{
		echo();
	}
	else
	{
		VFOR(i, v)
		echo(v);
	}
}
template <class T, class... Args>
void echovv(VV<T> v, Args... args)
{
	echovv(v);
	echovv(args...);
}
template <class Head> Head Min(Head head) { return head; }
template <class Head, class... Body>
Head Min(Head h, Body... b)
{
	auto t = Min(b...);
	return (h < t) ? h : t;
}
template <class Head> Head Max(Head head) { return head; }
template <class Head, class... Body>
Head Max(Head h, Body... b)
{
	auto t = Max(b...);
	return (h > t) ? h : t;
}

ll gcd(ll a, ll b)
{
	if (a < b)
	{
		a ^= b;
		b ^= a;
		a ^= b;
	}
	return b ? gcd(b, a % b) : a;
}
template <class... Body>
ll gcd(ll h, Body... b)
{
	return gcd(h, gcd(b...));
}

ll lcm(ll a, ll b) { return a / gcd(a, b) * b; }
template <class... Body>
ll lcm(ll h, Body... b)
{
	return lcm(h, lcm(b...));
}

ll Bset(ll a, ll b, ll c)
{
	if (c)
		a |= b;
	else
		a &= ~b;
	return a;
}

struct UF
{
  public:
	ll tsize;
	ll mode;
	vll par;
	vll rank;
	UF(){};
	UF(const UF &uf) {}
	UF(ll _size, ll _mode = 0)
	{
		tsize = _size;
		mode = _mode;
		par.assign(tsize, -1);
		if (!mode)
			rank.resize(tsize, 0);
	}
	ll root(ll x)
	{
		return par[x] < 0 ? x : par[x] = root(par[x]);
	}
	bool isRoot(ll x)
	{
		return root(x) == x;
	}
	void unite(ll x, ll y)
	{
		x = root(x);
		y = root(y);
		if (x == y)
			return;
		if (mode)
		{
			par[x] += par[y];
			par[y] += x;
		}
		else
		{
			if (rank[x] < rank[y])
			{
				par[y] += par[x];
				par[x] = y;
			}
			else
			{
				par[x] += par[y];
				par[y] = x;
				if (rank[x] == rank[y])
					rank[x]++;
			}
		}
	}
	bool same(ll x, ll y)
	{
		return root(x) == root(y);
	}
	ll size(ll x)
	{
		return -par[root(x)];
	}
};

class Vertex
{
  public:
	ll idx;
	ll param = -1;
	ll dist = INF;
	vector<pair<Vertex *, ll> /**/> e;
	ll size() { return e.size(); }
	bool operator==(const Vertex *o) { return dist == o->dist; }
	bool operator!=(const Vertex *o) { return dist != o->dist; }
	bool operator>(const Vertex *o) { return dist > o->dist; }
	bool operator<(const Vertex *o) { return dist < o->dist; }
	bool operator>=(const Vertex *o) { return dist >= o->dist; }
	bool operator<=(const Vertex *o) { return dist <= o->dist; }
};

class Graph
{
  public:
	vector<Vertex *> V;
	vll order;
	typedef tuple<Vertex *, Vertex *, ll> Edge;
	vector<Edge> E;
	Graph(ll siz)
	{
		REP(i, siz)
		{
			auto v = new Vertex();
			v->idx = i;
			V.pb(v);
		}
	}
	static bool comp(const Edge &e1, const Edge &e2)
	{
		return get<2>(e1) < get<2>(e2);
	}
	Vertex *getVertex(ll idx) { return V[idx]; }
	void unite(ll from, ll to, ll w = 1, bool digraph = true)
	{
		E.push_back(make_tuple(V[from], V[to], w));
		V[from]->e.pb(make_pair(V[to], w));
		if (!digraph)
		{
			E.push_back(make_tuple(V[to], V[from], w));
			V[to]->e.pb(make_pair(V[from], w));
		}
	}
	void dijkstra(ll start)
	{
		PQ<Vertex *, vector<Vertex *>, greater<Vertex *> /**/> pq;
		Vertex *s = getVertex(start);
		s->dist = 0;
		pq.push(s);
		while (!pq.empty())
		{
			Vertex *v = pq.top();
			pq.pop();
			for (auto &u : v->e)
			{
				if (u.first->dist > v->dist + u.second)
				{
					u.first->dist = v->dist + u.second;
					pq.push(u.first);
				}
			}
		}
	}
	bool sort(){
		for(auto &v : V){
			if(v->param==-1 && !sort_visit(v->idx)){
				return false;
			}
		}
		reverse(order.bn, order.ed);
		return true;
	}
	bool sort_visit(int v){
		Vertex *_v = getVertex(v);
		_v->param = 1;
		if(!_v->e.empty()){
			for(auto &u: _v->e){
				if(u.first->param == 2) continue;
				if(u.first->param == 1) return false;
				if(!sort_visit(u.first->idx)) return false;
			}
		}
		order.push_back(v);
		_v->param = 2;
		return true;
	}
};

ll isPrime(ll n)
{
	if (n <= 1)
		return 0;
	FOR(i, 2, (ll)sqrt(n))
	{
		if (n % i == 0)
			return 0;
	}
	return 1;
}

ll DigS10(ll n)
{
	ll m = 0;
	REP(i, DigN10(n)) { m += (ll)((llabs(n) % Pow10(i + 1))) / Pow10(i); }
	return m;
}

ll PowMod(ll a, ll b)
{
	ll ans = 1, x = a % MOD;
	REP(i, DigN2(b))
	{
		if (Dig2(b, i) == 1)
		{
			ans = (ans * x) % MOD;
		}
		if (i != (DigN2(b) - 1))
		{
			x = (x * x) % MOD;
		}
	}
	return ans;
}

vll FactMod(1, 1);
vll FactModInv(1, 1);
ll Mod(ll n)
{
	n %= MOD;
	n = (n + MOD) % MOD;
	return n;
}
ll InvM(ll n)
{
	n = Mod(n);
	n = PowMod(n, MOD - 2);
	return n;
}
void CFactMod(ll n)
{
	if (FactMod.size() <= n)
	{
		FOR(i, FactMod.size(), n)
		{
			FactMod.pb((FactMod[i - 1] * (i % MOD)) % MOD);
		}
	}
}
void CFactModInv(ll n)
{
	CFactMod(n);
	if (FactModInv.size() < (n + 1))
	{
		FactModInv.resize(n + 1, -1);
	}
	if (FactModInv[n] == -1)
	{
		FactModInv[n] = PowMod(FactMod[n], MOD - 2);
	}
	for (int i = n - 1; i >= 1; i--)
	{
		if (FactModInv[i] != -1)
			break;
		FactModInv[i] = ((FactModInv[i + 1] * ((i + 1) % MOD)) % MOD);
	}
}

ll CombMod(ll n, ll k)
{
	if (n < 0 || k < 0 || n < k)
		return 0;
	if (n + 1 > FactModInv.size())
		CFactModInv(n);
	return ((((FactModInv[k] * FactModInv[n - k]) % MOD) * FactMod[n]) % MOD);
}

pll factor_sub(ll n, ll m)
{
	ll i = 0;
	while (n % m == 0)
	{
		i++;
		n /= m;
	}
	return mp(i, n);
}

vpll factrization(ll n)
{
	vpll a;
	ll c, m;
	tie(c, m) = factor_sub(n, 2);
	if (c > 0)
		a.pb(mp(2, c));
	for (ll i = 3; m >= i * i; i += 2)
	{
		tie(c, m) = factor_sub(m, i);
		if (c > 0)
			a.pb(mp(i, c));
	}
	if (m > 1)
		a.pb(mp(m, 1));
	return a;
}

ll sumDigit(ll N) {
	ll sum = 0;
	for(ll i = 1; i <= N; i*= 10){
		sum += (N % (i * 10)) / i;
	}
	return sum;
}

signed main() {
	llin(A);
	llin(B);
	llin(K);
	ll m = min(A, B);
	ll ctr = 0;
	rFOR(i, 1, m) {
		if(A%i==0&&B%i==0){
			ctr++;
		}
		if(ctr==K){
			echo(i);
			return 0;
		}
	}
}


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

signed main(){

    int a, b, k; cin >> a >> b >> k;
    int num = 0;
    for(int i = max(a, b) ;; i--){
        if(a % i == 0 && b % i == 0){
            num++;
        }

        if(num == k){
            cout << i << endl;
            break;
        }
    }
    return 0;
}


#include<iostream>
#include<algorithm>
#include<math.h>
using namespace std;
int main (void)
{
  int i,a,b,k,d,gcd,c=0;
  cin>>a>>b>>k;
  while(1)
  {
    d=a%b;
    if(d==0){gcd=b;break;}
    a=b;
    b=d;
  }
  for(i=1;i<gcd;i++)
  {
    if(gcd%i==0)c++;
    if(c==k){break;}
  }
  cout<<i<<endl;
}


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

#define printl(s) cout << s << endl;
#define print(s) cout << s << endl; return 0;
#define yes cout << "Yes" << endl; return 0;
#define no cout << "No" << endl; return 0;
#define rep(i,n) for (int i = 0; i < (n); ++i)
#define rep2(i,n) for (int i = 1; i < (n)+1; ++i)
using ll = long long;

const ll modseed = pow(10,9) + 7;

template <typename T>
vector<T> getValues(ll num){
    vector<T> values(num);
    for(ll i=0;i<num;i++){
        cin >> values.at(i);
    }
    return values;
}

string S;
int A,B,C,K,N, cnt;

int main(){
  cin >> A >> B >> K;
  int len;
  rep2(i,min(A,B)){
    if(A%i==0 && B%i==0){
      len++;
      if(len==K){
        print(i);
      }
    }
  }
  print(cnt);
}


#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define ordered_set tree<ll, null_type , less<ll> , rb_tree_tag , tree_order_statistics_Node_update>
#define ll long long
#define ull unsigned long long
#define pb push_back
#define inf 1e18
#define mk make_pair
#define ld long double
#define mod 1000000007
#define fi first
#define se second
#define fastIO ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define test ll t; cin>>t; while(t--)
#define setbits __builtin_popcount
#define endl '\n'
#define LOCAL
#define sim template < class c
#define ris return * this
#define dor > debug & operator <<
#define eni(x) sim > typename \
enable_if<sizeof dud<c>(0) x 1, debug&>::type operator<<(c i) {
sim > struct rge { c b, e; };
sim > rge<c> range(c i, c j) { return rge<c>{i, j}; }
sim > auto dud(c* x) -> decltype(cerr << *x, 0);
sim > char dud(...);
struct debug {
#ifdef LOCAL
~debug() { cerr << endl; }
eni(!=) cerr << boolalpha << i; ris; }
eni(==) ris << range(begin(i), end(i));}
sim, class b dor(pair < b, c > d) {
    ris << "(" << d.first << ", " << d.second << ")";
}
sim dor(rge<c> d) {
    *this << "[";
    for (auto it = d.b; it != d.e; ++it)
        *this << ", " + 2 * (it == d.b) << *it;
    ris << "]";
}
#else
sim dor(const c&) { ris; }
#endif
};
#define imie(...) " [" << #__VA_ARGS__ ": " << (__VA_ARGS__) << "] "
int main()
{
    fastIO;
    ll x,y,k,val,val1;
    cin>>x>>y>>k;
    vector<ll>a;
    for(int i=1;i<=min(x,y);i++)
    {
        if(x%i==0 && y%i==0)
        {
            a.pb(i);
        }
    }
    sort(a.begin(),a.end());
    val=lower_bound(a.begin(),a.end(),k)-a.begin();
    cout<<a[val]<<endl;
}


#include <stdio.h>

int main(){
	int A,B,K;
  	int i,number,sum=0;
  	int wari[150]={0};

  if(scanf("%d %d %d", &A,&B,&K) < 3) {
    fprintf(stderr, "error: ill-formed fraction.\n");
}

  for(i=1;i<=110;i++){
  	if(A%i == 0 && B%i ==0) wari[i]=1;
    else;
   // printf("wari[%d]%d ",i,wari[i]);
  }

  for(i=110;i>0;i--){
  	sum+=wari[i];
    if(sum==K) break;
    else;
  }

  printf("%d",i);

  return 0;
}


#include <stdio.h>

int main(){
    int A,B,K ;
    int i,cnt,small;
    int a[101]={};
    int ans=0;
    cnt=0;

    scanf("%d %d %d",&A,&B,&K);
    if(A>B) small=B;
    else small=A;
    for(i=1;i<=small;i++){
        if(A%i==0 && B%i==0){
            cnt++;
            a[cnt]=i;
            // if(cnt==K) ans = i;
        }
    }
    //printf("%d\n",cnt);
    //for(i=0;i<=small;i++){
    //    printf("%d\n",a[i]);
    //}
    printf("%d\n",a[cnt-K+1]);

}


#include<stdio.h>
int main()
{
  int a,b,k,a_,amari,kouyaku,answer;
  scanf("%d %d %d",&a,&b,&k);
  if (a>b)  //bよりaを小さくする a<b
  {
    a_=a;
    a=b;
    b=a_;
  }
  while(1)
  {
    amari=b%a;
    if (amari==0)
    {
      kouyaku=a;
      break;
    }
    b=amari;
    a_=a;
    a=b;
    b=a_;
  }
  for( answer=kouyaku; answer>=1; answer-- )
  {
    if( kouyaku%answer == 0 ) k--;
    if (k==0) break;
  }
  printf("%d",answer);
  return 0;
}


#include<stdio.h>

int main()
{
    int A,B,K,i,x;
    int div[10];
    int n=0;
    scanf("%d %d %d", &A, &B, &K);
    if(A<B)
        x = A;
    else
        x=B;

    n=0;
    for(i=1; i<=x; i++)
    {
        if(A%i==0 && B%i==0)
        {
            div[n]=i;
            n++;
        }

    }

    printf("%d", div[K-1]);

    return 0;

}


#include<stdio.h>
int main()
{
    int a,b,c,i,sum=0;

    scanf("%d %d %d",&a,&b,&c);

    for(i=1;i>0;i++)
    {
        if(a%i==0 && b%i==0) sum++;

            if(sum==c) break;
            else continue;
    }

    printf("%d",i);

    return 0;
}


#include<stdio.h>

int main()
{
    int A,B,K,i,temp;
    int div[10];
    int n=0;
    scanf("%d %d %d", &A, &B, &K);

    if(B>A)
    {
        temp = A;
        A = B;
        B = temp;
    }
    n=0;
    for(i=1; i<=B; i++)
    {
        if(A%i==0 && B%i==0)
        {
            div[n]=i;
            n++;
        }

    }

    printf("%d", div[K-1]);

    return 0;

}


function Main(input) {

    input = input.split(" ");

    var a = parseInt(input[0], 10);
    var b = parseInt(input[1], 10);
    var k = parseInt(input[2], 10);

    var count = 0;
    var value = 0;

    for (var i = 100; i > -1; i--) {

        if ((a % i == 0) && (b % i == 0)) {
            count++;
        }

        if (count == k) {
            value = i;
            break;
        }

    }

    console.log(value);
}

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


// inputに入力データ全体が入る
function Main(input) {
    input = input.split("\n");
    tmp = input[0].split(" ");
    const a = parseInt(tmp[0], 10);
    const b = parseInt(tmp[1], 10);
    const c = parseInt(tmp[2], 10);

    //console.log(a,b,c);
    function divisor(num){
    var results = [];
   for(var i=1; i<=num; i++) {
        if( (num%i == 0) ) {
            results.push(i);
        }
    }
    return results;

    }
// テスト
p = divisor(a);
//console.log(p);
  q = divisor(b);
//console.log(q);
p1=p.length;q1=q.length;
//console.log(p1,q1);
var cnt =0;

ppp = [];qqq=[];
  if (p1 >= q1){
     for(i = 0;i<q1;i++){
      for (l=i;l<p1;l++){ if(q[i]==p[l]){ppp[cnt] = p[l];
                                     cnt =cnt +1;
                                   //  console.log(ppp);
                                     break; }

                        }
                       }
                   }
  else
    { for(i = 0;i<p1;i++){
      for (l=i;l<q1;l++){ if(p[i]==q[l]){ppp[cnt] = q[l];
                                     cnt =cnt +1;
                                  //   console.log(ppp);
                                     break; }
                         }
                         }
                        }

    t =ppp.length;
//  console.log(t-c);
    var t=t-c;
    console.log(ppp[t]);
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


'use strict';

function Main(input) {
  const A = Number(input.split(" ")[0])
  const B = Number(input.split(" ")[1])
  const K = Number(input.split(" ")[2])
  let counter = 0

  for (let i = Math.max(A, B); i > 0; i--) {
      if (A % i === 0 && B % i === 0) {
          counter++
      }
      if (counter === K) {
          console.log(i)
          return
      }
  }

};

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


function main(input) {
  const args = input.split(' ').map(n => parseInt(n, 10));
  const A = args[0],
        B = args[1],
        K = args[2];
  let cnt = 0;

  for (let i = 1; i <= 100; i++) {
    if (A % i === 0 && B % i === 0) {
      cnt++;
      if (cnt === K) {
        console.log(i);
        break;
      }
    }
  }
}

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


// Atcoder120 - B
function divisor(n) {var ret=[]; for (var i=1;i*i<=n;i++){if(n%i==0){ret.push(i);if(i*i!=n)ret.push(n/i);}}return ret;}
function main(input) {
  var inputs = input.split('\n');
  var abks = inputs[0].split(' ');
  var a = abks[0];
  var b = abks[1];
  var k = abks[2];

  var aDivisors = divisor(a);
  var bDivisors = divisor(b);

  var counter = 0;
  var kthCd = 0;
  aDivisors.sort((i, j) => i - j).some((item) => {
    counter += bDivisors.indexOf(item) >= 0 ? 1 : 0;
    if (counter == k) {
      kthCd = item;
      return true;
    }
  });

  console.log(kthCd);
}

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


// Atcoder120 - B
function divisor(n) {var ret=[]; for (var i=1;i*i<=n;i++){if(n%i==0){ret.push(i);if(i*i!=n)ret.push(n/i);}}return ret;}
function main(input) {
  var inputs = input.split('\n');
  var abks = inputs[0].split(' ');
  var a = abks[0];
  var b = abks[1];
  var k = abks[2];

  var aDivisors = divisor(a);
  var bDivisors = divisor(b);

  var counter = 0;
  var kthCd = 0;
  console.log(aDivisors.sort((i, j) => j - i));
  aDivisors.sort((i, j) => i - j).some((item) => {
    counter += bDivisors.indexOf(item) >= 0 ? 1 : 0;
    if (counter == k) {
      kthCd = item;
      return true;
    }
  });

  console.log(kthCd);
}

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


package main

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

func main() {
	fmt.Printf("%d\n", resolve(parseProblem(os.Stdin)))
}

func parseProblem(r io.Reader) (int, int, int) {
	const (
		initialBufSize = 100000
		maxBufSize     = 1000000
	)
	buf := make([]byte, initialBufSize)

	sc := bufio.NewScanner(r)
	sc.Buffer(buf, maxBufSize)
	sc.Split(bufio.ScanWords) // bufio.ScanLines
	a, b, k := scanInt(sc), scanInt(sc), scanInt(sc)
	return a, b, k
}

func resolve(a, b, k int) int {
	max := min(a, b)
	count := 0
	for i := max; i > 0; i-- {
		if a%i == 0 && b%i == 0 {
			count++
		}
		if count == k {
			return i
		}
	}
	// out of scope
	return -1
}
func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

// snip-scan-funcs
func scanInt(sc *bufio.Scanner) int {
	sc.Scan()
	i, _ := strconv.Atoi(sc.Text())
	return int(i)
}
func scanString(sc *bufio.Scanner) string {
	sc.Scan()
	return sc.Text()
}


package main

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

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

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

func main() {
	A := getInt()
	B := getInt()
	K := getInt()

	cnt := 0
	result := 0
	for i := min(A, B); i > 0; i-- {
		if A % i == 0 && B % i == 0 {
			cnt++
			result = i
		}
		if cnt == K {
			break
		}
	}
	fmt.Println(result)
}

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

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

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

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

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

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

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

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

			// なにか処理

			next = append(next, v)
		}
	}
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return true
}

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

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

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

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

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

	return result
}

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

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

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

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

type intHeap []int

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

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

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

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

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

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

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

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

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

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


package main

import (
  "fmt"
)

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

  var large int

  if a >= b {
    large = a
  } else if a < b{
  	large = b
  }

  ans := 0
  count := 0

  for i := large; i > 0; i-- {
//    fmt.Println("i:",i)
    if a%i == 0 && b%i == 0{
    	ans = i
    	count ++
    }

//    fmt.Println("ans:",ans)
//    fmt.Println("count:",count)

    if count == k {
    	break
    }

  }

  fmt.Println(ans)
}


package main

import (
	"fmt"
	"sort"
)

func main (){
	var a,b,k int
	fmt.Scan(&a, &b, &k)
	as := enumDivisions(a)
	bs := enumDivisions(b)
	cnt := 0
	for i := len(as)-1; i  > 0; i-- {
		for j := len(bs)-1; j > 0;j-- {
			if bs[j] == as[i] {
				cnt++
			}
			if cnt == k {
				fmt.Println(bs[j])
				return
			}

		}
	}

}

// 約数列挙
func enumDivisions(n int) []int {
	var res []int
	for i := 1; i * i <= n; i++ {
		if n % i == 0 {
			res = append(res, i)

			// 重複しないならばiの相方である n/i もappend
			if n/i != i {
				res = append(res, n/i)
			}
		}
	}
	// 小さい順に並び替える
	sort.Ints(res)
	return res
}


package main

import (
	"fmt"
	"math"
	"sort"
)

func divs(n, m int) (div []int) {
	min := int(math.Min(float64(n), float64(m)))
	if min == 1 {
		div = []int{1}
		return div
	}
	for i := 1; i < min; i++ {
		if n%i == 0 && m%1 == 0 {
			div = append(div, i)
		}
	}
	return div
}

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

	divs := divs(a, b)
	sort.Sort(sort.Reverse(sort.IntSlice(divs)))

	fmt.Println(divs[k-1])
}


inputs = STDIN.gets.chomp.split(' ').map(&:to_i)

# inputs => [A, B, K]

def factor(num)
  f = []
  i = 1
  while i <= num do
    if num % i == 0
      f << i
    end
    i += 1
  end
  f
end

div_a = factor inputs[0]
div_b = factor inputs[1]
div_common = div_a & div_b
div_common.reverse

puts div_common.reverse[inputs[2]-1]


input = gets
ary = input.split(" ")
ans=Array.new
ary[0].to_i.times{|n|
if (ary[0].to_i % (n+1) == 0 )and(ary[1].to_i % (n+1) == 0 )then
 ans.push(n+1)
end
}
print ans[ans.length-ary[2].to_i]


A, B, K = gets.split.map(&:to_i)

g = A.gcd(B)
puts g.downto(1).select{|x| g % x == 0}[K - 1]


line = gets.split(' ').map(&:to_i)

A = line[0]
B = line[1]
K = line[2]

num = 1
for i in 1..99 do
  if A % (100-i) == 0 and B % (100-i) == 0 then
    if num == K then
      puts 100 - i
      break
    else
      num += 1
    end
  end
end


line = gets.split(' ').map(&:to_i)

A = line[0]
B = line[1]
K = line[2]

num = 1
for i in 1..100 do
  if A % (100-i) == 0 and B % (100-i) == 0 then
    if num == K then
      puts 100 - i
      break
    else
      num += 1
    end
  end
end


line = gets.split(' ').map(&:to_i)

A = line[0]
B = line[1]
K = line[2]

num = 1
for i in 1..100 do
  if A % i == 0 and B % i == 0 then
    if num == K then
      puts i
      break
    else
      num += 1
    end
  end
end


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

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

fn main() {
    let a: usize = read();
    let b: usize = read();
    let k: usize = read();
    let mut arr = Vec::new();
    for i in 1..min(a, b) + 1 {
        if a % i == 0 && b % i == 0 {
            arr.push(i);
        }
    }
    arr.reverse();
    println!("{}", arr[k - 1]);
}


#![allow(dead_code, unused_variables, unused_macros, unused_imports)]

// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
macro_rules! input { (source = $s:expr, $($r:tt)*) => { let mut iter = $s.split_whitespace(); let mut next = || { iter.next().unwrap() }; input_inner!{next, $($r)*} }; ($($r:tt)*) => { let stdin = std::io::stdin(); let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock())); let mut next = move || -> String{ bytes .by_ref() .map(|r|r.unwrap() as char) .skip_while(|c|c.is_whitespace()) .take_while(|c|!c.is_whitespace()) .collect() }; input_inner!{next, $($r)*} }; }
macro_rules! input_inner { ($next:expr) => {}; ($next:expr, ) => {}; ($next:expr, $var:ident : $t:tt $($r:tt)*) => { let $var = read_value!($next, $t); input_inner!{$next $($r)*} }; ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => { let mut $var = read_value!($next, $t); input_inner!{$next $($r)*} }; }
macro_rules! read_value { ($next:expr, ( $($t:tt),* )) => { ( $(read_value!($next, $t)),* ) }; ($next:expr, [ $t:tt ; $len:expr ]) => { (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>() }; ($next:expr, chars) => { read_value!($next, String).chars().collect::<Vec<char>>() }; ($next:expr, usize1) => { read_value!($next, usize) - 1 }; ($next:expr, $t:ty) => { $next().parse::<$t>().expect("Parse error") }; }

fn main() {
    input! {
        a: usize,
        b: usize,
        k: usize
    }

    println!(
        "{}",
        (1..101)
            .filter(|&x| a % x == 0 && b % x == 0)
            .rev()
            .nth(k - 1)
            .unwrap()
    );
}


use std::io;

fn procon_read<T: std::str::FromStr>() ->  Vec<T> {
	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let iter = buf.split_whitespace();
	let mut v: Vec<T> = Vec::new();
	for i in iter {
		v.push(i.parse().ok().unwrap());
	}
	v
}

fn main() {
	let v:Vec<i32> = procon_read();
	let a = v[0];
	let b = v[1];
	let k = v[2];
	let mut cnt = 0;
	for i in (1..(a+1)).rev() {
		if a%i == 0 && b%i == 0 {
			cnt += 1;
		}
		if cnt == k {
			println!("{}", i);
			break;
		}
	}
}


use std::io::*;
use std::str::FromStr;
fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("failed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}
fn main(){
    let (a,b,k):(i64,i64,i64)=(read(),read(),read());
    let mut index:i64 =0;
    for i in 1..101{
        if a%i==0 {
            index+=1;
        }
        if index==k{
            println!("{}",i);
            return;
        }
    }
}


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

fn input_tuple() -> (u64, u64, u64) {
    let mut line: String = String::new();
    io::stdin().read_line(&mut line);
    let vec: Vec<u64> = line.split_whitespace().map(|s| s.parse().unwrap()).collect();
    (vec[0], vec[1], vec[2])
}

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

fn divisors(n: u64) -> Vec<u64> {
    let mut divisors: Vec<u64> = Vec::new();
    for i in 1..(n+1) {
        if i * i > n {
            break;
        }
        if n % i == 0 {
            divisors.push(i);
            if i * i != n {
                divisors.push(n / i);
            }
        }
    }
    divisors
}

fn main() {
    let (a, b, k) = input_tuple();
    let mut divisors = divisors(gcd(a, b));
    divisors.sort();
    println!("{:?}", divisors[(k-1) as usize]);
}


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

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

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

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

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

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

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

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

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

pub trait LexicalPermutation {
    /// Return `true` if the slice was permuted, `false` if it is already
    /// at the last ordered permutation.
    fn next_permutation(&mut self) -> bool;
    /// Return `true` if the slice was permuted, `false` if it is already
    /// at the first ordered permutation.
    fn prev_permutation(&mut self) -> bool;
}

impl<T> LexicalPermutation for [T]
where
    T: Ord,
{
    /// Original author in Rust: Thomas Backman <serenity@exscape.org>
    fn next_permutation(&mut self) -> bool {
        // These cases only have 1 permutation each, so we can't do anything.
        if self.len() < 2 {
            return false;
        }

        // Step 1: Identify the longest, rightmost weakly decreasing part of the vector
        let mut i = self.len() - 1;
        while i > 0 && self[i - 1] >= self[i] {
            i -= 1;
        }

        // If that is the entire vector, this is the last-ordered permutation.
        if i == 0 {
            return false;
        }

        // Step 2: Find the rightmost element larger than the pivot (i-1)
        let mut j = self.len() - 1;
        while j >= i && self[j] <= self[i - 1] {
            j -= 1;
        }

        // Step 3: Swap that element with the pivot
        self.swap(j, i - 1);

        // Step 4: Reverse the (previously) weakly decreasing part
        self[i..].reverse();

        true
    }

    fn prev_permutation(&mut self) -> bool {
        // These cases only have 1 permutation each, so we can't do anything.
        if self.len() < 2 {
            return false;
        }

        // Step 1: Identify the longest, rightmost weakly increasing part of the vector
        let mut i = self.len() - 1;
        while i > 0 && self[i - 1] <= self[i] {
            i -= 1;
        }

        // If that is the entire vector, this is the first-ordered permutation.
        if i == 0 {
            return false;
        }

        // Step 2: Reverse the weakly increasing part
        self[i..].reverse();

        // Step 3: Find the rightmost element equal to or bigger than the pivot (i-1)
        let mut j = self.len() - 1;
        while j >= i && self[j - 1] < self[i - 1] {
            j -= 1;
        }

        // Step 4: Swap that element with the pivot
        self.swap(i - 1, j);

        true
    }
}

#[cfg(not(debug_assertions))]
macro_rules! mydbg {
    ($($arg:expr),*) => {};
}

macro_rules! echo {
    ($($a:expr),*) => {
          $(println!("{}",$a))*
      }
}

use std::cmp::Ordering::*;
#[allow(unused_imports)]
use std::cmp::{max, min};
use std::collections::HashMap;
use std::io::{stdout, BufWriter, Write};
use std::mem::swap;

fn main() {
    input! {
        a: i32,
        b: i32,
        k: i32,
    }
    let mut candid:Vec<i32> = vec![];
    let mut ans = 0;
    for i in 1..100 {
       if a  % i == 0 && b % i == 0 {
           candid.push(i);
       }
    }
    for j in 0..k {
        ans = candid.pop().unwrap();
    }
    echo!(ans);
}


import Foundation

extension String {
    func split(separator: String) -> [Int] {
        return self.componentsSeparatedByString(separator).map { Int($0)! }
    }
}

let input = readLine()!.split(" ")
let A = input[0]
let B = input[1]
let K = input[2]

var divisor = [1]
for i in 2...100 {
    if (A % i == 0) && (B % i == 0) {
        divisor.append(i)
    }
}

print(divisor[divisor.count-K])


import Foundation

extension String {
    func split(separator: String) -> [Int] {
        return self.componentsSeparatedByString(separator).map { Int($0)! }
    }
}

let input = readLine()!.split(" ")
let A = input[0]
let B = input[1]
let K = input[2]

var divisor = [1]
for i in 2...100 {
    if (A % i == 0) && (B % i == 0) {
        divisor.append(i)
    }
}

print(divisor[divisor.count - (K-1)])


import Foundation

extension String {
    func split(separator: String) -> [Int] {
        return self.componentsSeparatedByString(separator).map { Int($0)! }
    }
}

let input = readLine()!.split(" ")
let A = input[0]
let B = input[1]
let K = input[2]

var divisor = [1]
for i in 2...100 {
    if (A % i == 0) && (B % i == 0) {
        divisor.append(i)
    }
    if divisor.count > K {
        break
    }
}

print(divisor[divisor.count - (K-1)])


import Foundation

extension String {
    func split(separator: String) -> [Int] {
        return self.componentsSeparatedByString(separator).map { Int($0)! }
    }
}

let input = readLine()!.split(" ")
let A = input[0]
let B = input[1]
let K = input[2]

var divisor: [Int] = []
for i in 1...100 {
    if (A % i == 0) && (B % i == 0) {
        divisor.append(i)
    }
    if divisor.count > K {
        break
    }
}

print(divisor[K-1])


const main = (input: string) => {
  const [A, B, K] = input.split(" ").map(str => parseInt(str))
  let divisorList = [];

  for (let i = 1; i <= A; i++) {
    if(A % i === 0 && B % i === 0) {
      divisorList.push(i)
    }
  }

  const answer = divisorList.reverse();
  console.log(answer[K - 1])
}

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


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

const inputlist = input.split(' ');

const a = Number(inputlist[0]);

const b = Number(inputlist[1]);

const k = Number(inputlist[2]);

const arr = [];

let e = 0;

if (a>b) {
  e = b;
} else {
  e = a;
}

for (let i=1;i<=e;i++) {
  if (a % i === 0 && b % i === 0) {
    arr.push(i);
  }
}

const f = arr.length - k;

console.log(arr[f]);


function main(input) {
  input = input.trim();
  const [a, b, k] = input.split(' ').map(n => Number(n));
  const array = [];
  for (let i = 1; i <= 100; i++) {
    if (a%i === 0 && b%i === 0) array.push(i);
  }
  const result = array[array.length-k]
  console.log(result);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function main(input) {
  const args = input.split(' ');
  let A = Number(args[0]);
  let B = Number(args[1]);
  let K = Number(args[2]);
  let cu = 0;
  let sum;
  let count = 0;
  for (cu = A; cu > 0; --cu) {
    if (Number.isInteger(A / cu) && Number.isInteger(B / cu)) {
      count++;
      if (count === K) {
        sum = cu;
        break;
      }
    }
  }
  console.log(sum);
}


function main(input) {
  const args = input.split(' ');
  let A = Number(args[0]);
  let B = Number(args[1]);
  let K = Number(args[2]);
  let Arr = A < B ? [A, B] : [B, A];
  let result = Array.from(Array(Arr[0]), (v, i) => i + 1).reduce((sum, cu) => {
    if (
      Number.isInteger(Arr[1] / cu)
    ) {
      sum.push(cu);
      return sum;
    }
    return sum;
  }, []);
  const res = result.splice(result.length - K, 1)[0];
  console.log(res);
}

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


function main(input) {
  const args = input.split(' ');
  let A = Number(args[0]);
  let B = Number(args[1]);
  let K = Number(args[2]);
  let [min, max] = A < B ? [A, B] : [B, A];
  let result = Array.from(Array(min), (v, i) => i + 1).reduce((sum, cu) => {
    if (Number.isInteger(min / cu) && Number.isInteger(max / cu)) {
      sum.push(cu);
      return sum;
    }
    return sum;
  }, []);
  const res = result.splice(result.length - K, 1)[0];
  console.log(res);
}


A,B=map(int,input().split())
if A==2 or B==2:
	print("No")
elif A==4 or A==6 or A==9 or A==11:
	if B==4 or B==6 or B==9 or B==11:
		print("Yes")
	else:
		print("No")
else:
	if B==4 or B==6 or B==9 or B==11:
		print("No")
	else:
		print("Yes")


n,m=map(int,input().split())

a=[4,6,9,11]
b=[1,3,5,7,8,10,12]

if (n in a and m in a) or (n in b and m in b):print('Yes')

else:print('No')


a={1,3,5,7,8,10,12}
b={4,6,9,11}
c={2}
xy=set(map(int,input().split()))
if xy.issubset(a) or xy.issubset(b) or xy.issubset(c):
  print("Yes")
else:
  print("No")


x, y = map(int,input().split())
S1 = [1, 3, 5, 7, 8, 10, 12]
S2 = [4, 6, 9, 11]
for i in range(len(S1)):
  for j in range(len(S1)):
    if (S1[i] == x and s1[j] == y) or (S2[i] == x adn S2[j] == y):
      print("Yes")
    else:
      print("No")


H, W = [int(x) for x in input().split()]
pic = [list(input()) for _ in range(H)]
ans = [['#' for i in range(W+2)] for j in range(H+2)]
for i in range(W):
  for j in range(H):
    ans[j+1][i+1] = pic[j][i]
for i in range(H+2):
  print(*ans[i])


x,y=map(int,input().split())
group_A=[1,3,5,7,8,10,12]
group_B=[4,6,9,11]
if x in group_A ==True and y in group_A ==True:
  print("Yes")
elif x in group_B == True and y in group_B ==True:
  print("Yes")
else:
  print("No")


//package com.zhangyong.algorithm;

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

public class Main {

    FastScanner in;
    PrintWriter out;

    class FastScanner {

        BufferedReader br;
        StringTokenizer st;

        private FastScanner(File f) {
            try {
                br = new BufferedReader(new FileReader(f));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }

        private FastScanner(InputStream f) {
            br = new BufferedReader(new InputStreamReader(f));
        }

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

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

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

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

    }

    private void solve() {
        //0 31 29 31 30 31 30 31 31 30 31 30 31
        int[] arr = new int[]{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        int x, y;
        x = in.nextInt();
        y = in.nextInt();
        if (arr[x] == arr[y]) {
            out.println("Yes");
        } else {
            out.println("No");
        }
    }

    private void run() {
        in = new FastScanner(System.in);
        out = new PrintWriter(System.out);
        solve();
        out.close();
    }

    public static void main(String[] args) {
        new Main().run();
    }
}


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

public class Main {

	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		String s = br.readLine();
		String[] array = s.split(" ");

		int a = Integer.parseInt(array[0]);
		int b = Integer.parseInt(array[1]);

		if ((a == 1 || a == 3 || a == 5 || a == 7 || a == 8 || a == 10 || a == 12)
				&& (b == 1 || b == 3 || b == 5 || b == 7 || b == 8 || b == 10 || b == 12)) {
			System.out.println("Yes");
		} else if ((a == 4 || a == 6 || a == 9 || a == 11) && (b == 4 || b == 6 || b == 9 || b == 11)) {
			System.out.println("Yes");
		} else if ((a == 2) && (b == 2)) {
			System.out.println("Yes");
		} else
			System.out.println("No");
		{

		}
	}
}


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

public class Main{
    public void run(){
        try(BufferedReader br = new BufferedReader(new InputStreamReader(System.in))){
            String[] arg = br.readLine().split(" ");
            List<Integer> list = Arrays.asList(1,3,5,7,8,10,12);
            List<Integer> list2 = Arrays.asList(4,6,9,11);
            List<Integer> list3 = Arrays.asList(2);
            if(list.contains(Integer.parseInt(arg[0])) && list.contains(Integer.parseInt(arg[1]))){
                System.out.println("Yes");
                return;
            }
            if(list2.contains(Integer.parseInt(arg[0])) && list2.contains(Integer.parseInt(arg[1]))){
                System.out.println("Yes");
                return;
            }
            if(list3.contains(Integer.parseInt(arg[0])) && list3.contains(Integer.parseInt(arg[1]))){
                System.out.println("Yes");
                return;
            }
            System.out.println("No");
        }catch(Exception e){

        }
    }
    public static void main(String... args){
        new Main().run();
    }}


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

public class Main{
	public static void main(String[] args)  throws IOException,NumberFormatException{
		try {
		FastScanner sc=new FastScanner();
		int x=sc.nextInt(),y=sc.nextInt();
		String a="1 3 5 7 8 10 12";
		String b="4 6 9 11";
		String c="2";
		boolean ans=false;
		if(a.contains(String.valueOf(x))&&a.contains(String.valueOf(y)))ans=true;
		if(b.contains(String.valueOf(x))&&b.contains(String.valueOf(y)))ans=true;
		if(c.contains(String.valueOf(x))&&c.contains(String.valueOf(y)))ans=true;

		System.out.println(ans?"Yes":"No");

		}
		catch(Exception e) {
			return ;
		}

	}
	static final Random random=new Random();

	static void ruffleSort(int[] a) {
		int n=a.length;
		for(int i=0;i<n;i++) {
			int oi=random.nextInt(n),temp=a[oi];
			a[oi]=a[i]; a[i]=temp;
		}
		Arrays.sort(a);
	}

	public static class FastScanner {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st=new StringTokenizer("");
		String next() {
			while (!st.hasMoreTokens())
				try {
                                      st=new StringTokenizer(br.readLine());
                              } catch (IOException e) {}
			return st.nextToken();
		}

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

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

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

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

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

}


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

public class Main{
	public static void main(String[] args)  throws IOException,NumberFormatException{
		try {
		FastScanner sc=new FastScanner();
		int x=sc.nextInt(),y=sc.nextInt();
		String a="135781012";
		String b="46911";
		String c="2";
		boolean ans=false;
		if(a.contains(String.valueOf(x))&&a.contains(String.valueOf(y)))ans=true;
		if(b.contains(String.valueOf(x))&&b.contains(String.valueOf(y)))ans=true;
		System.out.println(ans?"Yes":"No");

		}
		catch(Exception e) {
			return ;
		}

	}
	static final Random random=new Random();

	static void ruffleSort(int[] a) {
		int n=a.length;
		for(int i=0;i<n;i++) {
			int oi=random.nextInt(n),temp=a[oi];
			a[oi]=a[i]; a[i]=temp;
		}
		Arrays.sort(a);
	}

	public static class FastScanner {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st=new StringTokenizer("");
		String next() {
			while (!st.hasMoreTokens())
				try {
                                      st=new StringTokenizer(br.readLine());
                              } catch (IOException e) {}
			return st.nextToken();
		}

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

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

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

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

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

}


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

public class Main {

	private static final int mod =(int)1e9+7;
	public static void main(String[] args) throws Exception  {
	      Scanner  sc=new Scanner(System.in);
	      PrintWriter out=new PrintWriter(System.out);
	        int n=sc.nextInt();
	       long a[]=new long[3*n];
	        for(int i=0;i<3*n;i++) {
	          a[i]=sc.nextLong();
	        }
	        long ans=Long.MIN_VALUE;
	        PriorityQueue<Long> pq=new PriorityQueue<>();
	        ArrayList<Long> sum=new ArrayList<>();
	        ArrayList<Long> sum2=new ArrayList<>();
	        long summ=0;
	        for(int i=0;i<n;i++) {
	          pq.add(a[i]);
	          summ+=a[i];

	        }
	       sum.add(summ);
	        for(int i=n;i<2*n;i++) {
	          pq.add(a[i]);
	          summ+=a[i];
	           summ-= pq.poll();

	            sum.add(summ);

	        }
	        PriorityQueue<Long> pq1=new PriorityQueue<>(Collections.reverseOrder());
	        long summ1=0;
         for(int i=3*n-1;i>=2*n;i--) {
           pq1.add(a[i]);
           summ1+=a[i];

         }
         sum2.add(summ1);
         for(int i=2*n-1;i>=n;i--) {
           pq1.add(a[i]);
           summ1+=a[i];
            summ1-= pq1.poll();

             sum2.add(summ1);

         }

         for(int i=1;i<=n;i++) {
           ans=Math.max(sum.get(i)-sum2.get(n-i),ans);
         }

	        System.out.println(ans);
	}
	static long solve(PriorityQueue<Long> pq) {

	  long sum=0;

	       while(!pq.isEmpty()) {
	         sum+=pq.poll();

	       }
	       return sum;
	}
 static long solve1(long a[],int i,int j,int n) {

   PriorityQueue<Long> pq=new PriorityQueue<>();
   for(int k=i;k<j;k++) {

     pq.add(a[k]);
   }

   long sum=0;
  while(n!=0) {
    sum+=pq.poll();
    n--;
  }
  return sum;
}

	static int  prime[]=new int[100001];
	static void sieve() {
	  Arrays.fill(prime,1);
	  prime[0]=0;
	  prime[1]=1;
	  for(int i=2;i*i<100001;i++) {
	   if(prime[i]!=0) {
	     for(int j=i;j<10001;j+=i) {
	       prime[j]=0;
	     }
	   }
	  }
	}
	      static long gcd(long a, long b)
	      {
	          if (a == 0)
	              return b;
	          return gcd(b % a, a);
	      }

static long nCr(int n,int r) {
  int dp[][]=new int[2001][2001];
  for(int i=0;i<2001;i++) {
    dp[0][i]=0;
  }
  for(int i=0;i<2001;i++) {
    dp[i][0]=1;
  }
  for(int i=1;i<2001;i++) {
    for(int j=1;j<2001;j++) {
      if(i==j) {
        dp[i][j]=1;
      }else {
        dp[i][j]=dp[i-1][j-1]+dp[i][j-1];
      }
    }
  }
  return dp[n][r];
}

}
class pair {
  int src;
 int  des;
 long val;
  pair(int src,int des,long val){
    this.src=src;
    this.des=des;
    this.val=val;

  }

//  @Override
//  public int compareTo(pair o) {
//
//    return this.wt-o.wt;
//  }
}


#include <stdio.h>
#include <algorithm>
int main() {
	int x, y;
	scanf("%d %d", &x, &y);
	int gx, gy;
	switch (x)
	{
	case 1:
	case 3:
	case 5:
	case 7:
	case 8:
	case 10:
	case 12:
		gx = 0;
		break;
	case 4:
	case 6:
	case 9:
	case 11:
		gx = 1;
		break;
	case 2:
		gx = 2;
		break;
	default:
		gx = 3;
		break;
	}
	switch (y)
	{
	case 1:
	case 3:
	case 5:
	case 7:
	case 8:
	case 10:
	case 12:
		gy = 0;
		break;
	case 4:
	case 6:
	case 9:
	case 11:
		gy = 1;
		break;
	case 2:
		gy = 2;
		break;
	default:
		gy = 3;
		break;
	}
	printf("%s\n", (gx == gy ? "Yes" : "No"));
}


#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
int flag[15];
int x,y;

int main()
{
	scanf("%d%d",&x,&y);
	flag[1] = flag[3] = flag[5] = flag[7] = flag[8] = flag[10] = flag[12] = 1;
    flag[4] = flag[6] = flag[9] = flag[11] = 2;
    if(flag[x] == flag[y]) printf("Yes\n");
    else printf("No\n");

	return 0;
}


#include<stdio.h>
#include<math.h>
using namespace std;
int main(){
	int x,y;
	int n[13]={0,1,2,1,3,1,3,1,1,3,1,3,1};
	scanf("%d%d",&x,&y);
	if(n[x]==n[y])	printf("Yes\n");
	else	printf("No\n");
	return 0;
}


#include <iostream>
using namespace std;
int main()
{
  int gp[3][7] = {
    {1,3,5,7,8,10,12},
    {4,6,9,11},
    {2},
  };
  int x, y;
  cin >> x >> y;
  int xg= 0, yg = 0;
  for (int i = 0; i < 3; i++) {
    for (int j = 0; j < sizeof(gp[i]/sizeof(int)); j++) {
      if (gp[i][j] == x) {
        xg = i;
      }
      if (gp[i][j] == y) {
        yg = i;
      }
    }
  }
  if (xg == yg) {
    cout << "Yes" << endl;
  } else {
    cout << "No" << endl;
  }
  return 0;
}


#include <iostream>
using namespace std;
int main()
{
  int gp[3][] = {
    {1,3,5,7,8,10,12},
    {4,6,9,11},
    {2},
  };
  int x, y;
  cin >> x >> y;
  int xg= 0, yg = 0;
  for (int i = 0; i < 3; i++) {
    for (int j = 0; j < sizeof(gp[i]/sizeof(int)); j++) {
      if (gp[i][j] == x) {
        xg = i;
      }
      if (gp[i][j] == y) {
        yg = i;
      }
    }
  }
  if (xg == yg) {
    cout << "Yes" << endl;
  } else {
    cout << "No" << endl;
  }
  return 0;
}


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

int main(){
	vector<int> x(2);
	cin >> x.at(0) >> x.at(1);
	for(int i=0; i<2; i++){
		if(x.at(i)==2) x.at(i)=2;
		if(x.at(i)==4 || x.at(i)==6 || x.at(i)==9 || x.at(i)==11) x.at(i)=1;
		else x.at(i)=0;
	}
	if(x.at(0)==x.at(1)) cout << "Yes" << endl;
	else cout << "No" << endl;
}


#include <stdio.h>

int main(){
    int g[12] = {1,3,1,2,1,2,1,1,2,1,2,1};
    int a, b;
    scanf("%d%d", &a, &b);
    printf(g[a-1] == g[b-1] ? "Yes\n" : "No");
    return 0;
}


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

int main() {
  int i, j;
  int x, y;

  int nums[] = {-1, 1, 3, 1, 2, 1, 2, 1, 1, 2, 1, 2, 1};

  scanf("%d %d", &x, &y);

  if (nums[x] == nums[y]) {
    printf("Yes");
  }
  else {
    printf("No");
  }

  return 0;
}


#include<stdio.h>
int main(void)
{
  int g1[7]={1,3,5,7,8,10,12};
  int g2[4]={4,6,9,11};
  int x,y;
  scanf("%d %d",&x,&y);

  if(x==y){
    puts("Yes");
    return 0;
  }

  int flag1=0;
  for(int i=0;i<7;i++){
    if(g1[i]==x){
      flag1=1;
    }
    if(flag1==1&&g1[i]==y){
      puts("Yes");
      return 0;
    }
  }

  int flag2=0;
  for(int i=0;i<4;i++){
    if(g2[i]==x){
      flag2=1;
    }
    if(flag2==1&&g2[i]==y){
      puts("Yes");
      return 0;
    }
  }

  puts("No");

  return 0;
}


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

int x, y;
scanf("%d %d", &x, &y);

    if(x==2||y==2){
        printf("No\n");
    }
    else if((x==1||x==3||x==5||x==7||x==8||x==10||x==12)&&(y==1||y==3||y==5||y==7||y==8||y==10||y==12))
    {
        printf("Yes\n");
    }
    else if((x==4||x==6||x==9||x==11)&&(y==4||y==6||y==9||y==11))
    {
        printf("YES");
    }
    else{
        printf("NO");
    }

return 0;

}


#include<stdio.h>
#include<bits/stdc++.h>
using namespace std;
int main()
{
    int x,y,z;
    cin>>x>>y;
    if(x==2 || y==2)
        cout<<"No"<<endl;
    else if(x==4 || x==6 || x==9 || x==12)
        if(y==4 || y==6 || y==9 || y==12)
            cout<<"Yes"<<endl;
        else
            cout<<"No"<<endl;
    else if(x== 3 || x==1 || x==5 || x==7 || x==8 || x==10 || x==12)
        if(y==3 || y==1 || y==5 || y==7 || y==8 || y==10 || y==12)
            cout<<"yes"<<endl;
        else
            cout<<"No"<<endl;
    else
        cout<<"No"<<endl;
    return 0;

}


int main()
{
    int x,y,z;
    cin>>x>>y;
    if(x==2 || y==2)
        cout<<"No"<<endl;
    else if(x==4 || x==6 || x==9 || x==12)
        if(y==4 || y==6 || y==9 || y==12)
            cout<<"Yes"<<endl;
        else
            cout<<"No"<<endl;
    else if(x== 3 || x==1 || x==5 || x==7 || x==8 || x==10 || x==12)
        if(y==3 || y==1 || y==5 || y==7 || y==8 || y==10 || y==12)
            cout<<"yes"<<endl;
        else
            cout<<"No"<<endl;
    else
        cout<<"No"<<endl;
    return 0;

}


function Main(input){
  input = input.split(' ');
  var x = Number(input[0]);
  var y = Number(input[1]);

  var group_a = [1,3,5,7,8,10,12];
  var group_b = [4,6,9,11];
  var group_c = [2];

  if( group_a.indexOf(x) > -1 && group_a.indexOf(y) > -1 ||
  group_b.indexOf(x) > -1 && group_b.indexOf(y) > -1 ||
  group_c.indexOf(x) > -1 && group_c.indexOf(y) > -1) {
      console.log('Yes');
  } else {
      console.log('No');
  }

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


"use strict"

function main(input) {

  input = input.split(' ').map(v => ~~v)
  const x = input[0]
  const y = input[1]
  const a = [1, 3, 5, 7, 8, 10, 12]
  const b = [4, 6, 9, 11]
  // const c = [2]

  // console.log(a.indexOf(x), a.indexOf(y), b.indexOf(x), b.indexOf(y))
  if ((a.indexOf(x) >= 0 && a.indexOf(y) >= 0) ||
    (b.indexOf(x) >= 0 && b.indexOf(y) >= 0)) {
    console.log('Yes')
    return
  }
  console.log('No')
}
main(require("fs").readFileSync("/dev/stdin", "utf8"));


'use strict'

const main = input => {
	const args = input.split('\n').map(arg => arg.split(' '))
	const x = parseInt(args[0][0], 10)
	const y = parseInt(args[0][1], 10)
	const group1 = [1, 3, 5, 7, 8, 10, 12]
	const group2 = [4, 6, 9, 11]

	let f1 = false
	let f2 = false

	for (let i = 0; i < group1.length; i++) {
		if (x === group1[i]) f1 = true
		if (y === group1[i]) f2 = true
	}

	let f3 = false
	let f4 = false

	for (let i = 0; i < group2.length; i++) {
		if (x === group2[i]) f3 = true
		if (y === group2[i]) f4 = true
	}

	if (f1 && f2) console.log('Yes')
	else if (f3 && f4) console.log('Yes')
	else console.log('No')
}

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


function Main(input) {
  input = input.trim()
  input = input.split(" ");
  if(hoge(input[1])==hoge(input[0])){
  console.log("Yes")
  }else{
  console.log("No")
  }
}Main(require("fs").readFileSync("/dev/stdin", "utf8"));
function hoge(n){
if(n==1||n==3|n==5||n==7||n==8||n==12) return 1;
  else if(n==2) return 3;
  else return 2;
}


function main(input) {
  input=input.trim();
  const x = parseInt(input.split(" ")[0], 10);
  const y = parseInt(input.split(" ")[1], 10);
  var wake=function(n){
    if(n==1||n==3||n==5||n==7||n==8||n==10||n==12){
      return a
    }else if(n==4||n==6||n==9||n==11){
      return b
    }else{
      return c
    }
  }
  if(wake(x)==wake(y)){
    console.log("Yes");
  }else{
    console.log("No");
  }
}

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


function Main(input) {
  const numbers = input.split(' ').map(n => Number(n));
  const x = numbers[0];
  const y = numbers[1];
  const array1 = [1,3, 5, 7, 8, 10, 12];
  const array2 = [4, 6, 9, 11];
  const array3 = [2]

  if((array1.includes(x) && array1.includes(y))
   || (array2.includes(x) && array2.includes(y))
   || (array3.includes(x) && array3.includes(y))) {
     console.log('Yes');
  } else {
    console.log('No');
  }
}

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


package main

import "fmt"

func main() {
	group := make([]int, 12+1)
	for _, b := range []int{4, 6, 9, 11} {
		group[b] = 1
	}
	for _, c := range []int{2} {
		group[c] = 2
	}

	var x, y int
	fmt.Scanf("%d %d", &x, &y)
	if group[x] == group[y] {
		fmt.Println("Yes")
	} else {
		fmt.Println("No")
	}
}


package main

import (
	"fmt"
)

func main() {
	s := []int{0, 2, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0}
	var x, y int
	fmt.Scan(&x, &y)
	if s[x-1] == s[y-1] {
		fmt.Println("Yes")
	} else {
		fmt.Println("No")
	}
}


package main

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

func out(x ...interface{}) {
	fmt.Println(x...)
}

var sc = bufio.NewScanner(os.Stdin)

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

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

// min, max, asub, absなど基本関数
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

func asub(a, b int) int {
	if a > b {
		return a - b
	}
	return b - a
}

func abs(a int) int {
	if a >= 0 {
		return a
	}
	return -a
}

func lowerBound(a []int, x int) int {
	idx := sort.Search(len(a), func(i int) bool {
		return a[i] >= x
	})
	return idx
}

func upperBound(a []int, x int) int {
	idx := sort.Search(len(a), func(i int) bool {
		return a[i] > x
	})
	return idx
}

func chk(x int) int {
	if x == 2 {
		return 3
	}
	if x == 4 || x == 6 || x == 9 || x == 11 {
		return 2
	}
	return 1
}

func main() {
	sc.Split(bufio.ScanWords)
	x, y := getInt(), getInt()
	if chk(x) == chk(y) {
		out("Yes")
		return
	}
	out("No")
}


package main

import (
	"fmt"
)

func isA(a int) bool {
	switch a {
	case 1, 3, 5, 7, 8, 10, 12:
		fmt.Println(a)
		return true
	}
	return false
}

func isB(a int) bool {
	switch a {
	case 4, 6, 9, 11:
		return true
	}
	return false
}

func isC(a int) bool {
	if a == 2 {
		return true
	}
	return false
}

func main() {
	var x, y int
	fmt.Scan(&x, &y)

	if (isA(x) && isA(y)) ||
		(isB(x) && isB(y)) ||
		(isC(x) && isC(y)) {
		fmt.Println("Yes")
	} else {
		fmt.Println("No")
	}

}


package main

import (
	"fmt"
)

func main() {
	s := []int{0, 2, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1}
	var x, y int
	fmt.Scan(&x, &y)
	if s[x-1] == s[y-1] {
		fmt.Println("Yes")
	} else {
		fmt.Println("No")
	}
}


func main() {
	group := make([]int, 12+1)
	for _, b := range []int{4, 6, 9, 11} {
		group[b] = 1
	}
	for _, c := range []int{2} {
		group[c] = 2
	}

	var x, y int
	fmt.Scanf("%d %d", &x, &y)
	if group[x] == group[y] {
		fmt.Println("Yes")
	} else {
		fmt.Println("No")
	}
}


def id(x)
  case x
  when 1,3,5,7,8,10,12 then 1
  when 4,6,9,11 then 2
  else 3
  end
end

x,y = gets.split.map(&:to_i)
puts id(x) == id(y) ? "Yes" : "No"


puts gets.include?("2") ? "No" : "Yes"


x, y = gets.split.map(&:to_i)
arr = [-1, 1, 3, 1, 2, 1, 2, 1, 1, 2, 1, 2, 1]
puts arr[x]==arr[y] ? "Yes" : "No"


a=gets.split.map do |i|
  i = i.to_i
  i==2 ? 2 : [1,3,5,7,8,10,12].include?(i) ? 1 : 0
end
puts a.uniq.size==2 ? "Yes" : "No"


# すぬけ君は、1 から 12 までの整数を下図のようにグループ分けしました。
# 整数 x, y (1≤x<y≤12) が与えられるので、x, y が同一のグループに属しているか判定してください。

input = gets.chomp.split
x = input[0].to_i
y = input[1].to_i

groups = [
    [1, 3, 5, 7, 8, 10, 12],
    [4, 6, 9, 11],
    [2]
]

3.times do |i|
    if x.include?(groups[i]) && y.include?(groups[i])
        puts "Yes"
        break
    end
    if i == 2
        puts "No"
    end
end


x, y = gets.split.map(&:to_i)
array = [0, 1, 3, 1, 2, 1, 2, 1, 1, 2, 1, 2, 1]
puts array[x] == array[y] ? "Yes" : "no"


use std::io;
use std::collections::HashSet;

fn procon_read<T: std::str::FromStr>() ->  Vec<T> {
	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let iter = buf.split_whitespace();
	let mut v: Vec<T> = Vec::new();
	for i in iter {
		v.push(i.parse().ok().unwrap());
	}
	v
}

fn main() {
	let v:Vec<i32> = procon_read();
	let x = v[0];
	let y = v[1];
	let mut set1:HashSet<i32> = HashSet::new();
	set1.insert(1);
	set1.insert(3);
	set1.insert(5);
	set1.insert(7);
	set1.insert(8);
	set1.insert(10);
	set1.insert(12);
	let mut set2:HashSet<i32> = HashSet::new();
	set2.insert(4);
	set2.insert(6);
	set2.insert(9);
	set2.insert(11);
	let mut set3:HashSet<i32> = HashSet::new();
	set3.insert(2);
	let mut flag = false;
	if !set1.insert(x) && !set1.insert(y) {
		flag = true;
	}
	if !set2.insert(x) && !set2.insert(y) {
		flag = true;
	}
	if !set3.insert(x) && !set3.insert(y) {
		flag = true;
	}
	if flag {
		println!("Yes");
	}else{
		println!("No");
	}
}


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

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

struct UnionFind {
    parent: Vec<usize>,
    size: Vec<usize>,
}

impl UnionFind {
    fn new(n: usize) -> UnionFind {
        // initialize
        let mut v: Vec<usize> = vec![];
        for i in 0..n + 1 {
            v.push(i)
        }
        let mut s: Vec<usize> = vec![1; n + 1];

        UnionFind { parent: v, size: s }
    }

    fn root(&self, x: usize) -> usize {
        if self.parent[x] == x {
            return x;
        } else {
            return self.root(self.parent[x]);
        }
    }

    fn size(&self, a: usize) -> usize {
        let ra = self.root(a);
        self.size[ra]
    }

    fn unite(&mut self, a: usize, b: usize) {
        let mut ra = self.root(a);
        let mut rb = self.root(b);
        if ra == rb {
            return;
        }
        if self.size[ra] < self.size[rb] {
            std::mem::swap(&mut ra, &mut rb)
        };
        self.size[ra] += self.size[rb];
        self.parent[rb] = ra;
    }

    fn same(&self, a: usize, b: usize) -> bool {
        let ra = self.root(a);
        let rb = self.root(b);
        self.parent[a] == self.parent[b]
    }
}

fn main() {
    let mut uf = UnionFind::new(12);
    uf.unite(1, 3);
    uf.unite(1, 5);
    uf.unite(1, 7);
    uf.unite(1, 8);
    uf.unite(1, 10);
    uf.unite(1, 12);

    uf.unite(4, 6);
    uf.unite(4, 9);
    uf.unite(4, 11);
    let x: usize = read();
    let y: usize = read();
    if uf.same(x, y) {
        println!("Yes");
    } else {
        println!("No");
    }
}


macro_rules! get {
    ($t:ty) => {
        {
            let mut line: String = String::new();
            std::io::stdin().read_line(&mut line).unwrap();
            line.trim().parse::<$t>().unwrap()
        }
    };
    ($($t:ty),*) => {
        {
            let mut line: String = String::new();
            std::io::stdin().read_line(&mut line).unwrap();
            let mut iter = line.split_whitespace();
            (
                $(iter.next().unwrap().parse::<$t>().unwrap(),)*
            )
        }
    };
    ($t:ty; $n:expr) => {
        (0..$n).map(|_|
            get!($t)
        ).collect::<Vec<_>>()
    };
    ($($t:ty),*; $n:expr) => {
        (0..$n).map(|_|
            get!($($t),*)
        ).collect::<Vec<_>>()
    };
}

fn main() {
    let ms = [0,1,3,1,2,1,2,1,1,2,1,2,1];
    let (x, y) = get!(usize, usize);
    println!("{}", if ms[x] == ms[y] { "Yes" } else { "No" });
}