jiahuimbzuai/CoQuIR huggingface dataset:
//  [go]
package main

import "fmt"

var N, K int

func main() {
	fmt.Scan(&N, &K)
	ComInit(N+1)
	ans := 0
	for i := K; i<=N+1; i++ {
		ans = Madd(ans+1, Mmul(i, N-i+1))
	}
	fmt.Println(ans)
}

var fac, finv []int

func ComInit(N int) { comInit(N, MOD) }
func comInit(N int, mod int) {
	fac = make([]int, N+1)
	finv = make([]int, N+1)
	fac[0] = 1
	fac[1] = 1
	finv[0] = 1
	finv[1] = 1

	for i := 2; i <= N; i++ {
		fac[i] = mmul(fac[i-1], i, mod)
		finv[i] = mmul(finv[i-1], minv(i, mod), mod)
	}
}

func Com(n, k int) int { return com(n, k, MOD) }
func com(n, k, mod int) int {
	if n < k {
		return 0
	}
	if n < 0 || k < 0 {
		return 0
	}
	return mmul(fac[n], mmul(finv[k], finv[n-k], mod), mod)
}

const MOD = 1000000007

func Madd(a, b int) int { return madd(a, b, MOD) }
func madd(a, b, mod int) int {
	if a+b > mod {
		return a + b - mod
	}
	return a + b
}

func Msub(a, b int) int { return msub(a, b, MOD) }
func msub(a, b, mod int) int {
	if a-b < 0 {
		return a - b + mod
	}
	return a - b
}

func Mmul(a, b int) int { return mmul(a, b, MOD) }
func mmul(a, b, mod int) int {
	return ((a % mod) * (b % mod)) % mod
}

func Mpow(a, b int) int { return mpow(a, b, MOD) }
func mpow(k, p, mod int) int {
	r := 1
	for ; p > 0; p >>= 1 {
		if p&1 == 1 {
			r = mmul(r, k, mod)
		}
		k = mmul(k, k, mod)
	}
	return r
}

func Minv(a int) int { return minv(a, MOD) }
func minv(a, mod int) int {
	b := mod
	u, v := 1, 0
	for b > 0 {
		t := a / b
		a -= t * b
		a, b = b, a
		u -= t * v
		u, v = v, u
	}
	u %= mod
	if u < 0 {
		u += mod
	}
	return u
}

func Mdiv(a, b int) int { return mdiv(a, b, MOD) }
func mdiv(a, b, mod int) int {
	return mmul(a, minv(b, mod), mod)
}
//  [go]
package main

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

func main() {
	N := nextInt64()
	K := nextInt64()

	c := mint(0)

	for i := mint(K); i <= mint(N+1); i++ {
		min := i.mul(i - 1).div(2)     // 0 + 1 + 2 + 3 + ... + i - 1
		max := mint(N).mul(i).sub(min) // N + (N - 1) + ... + (N - (i - 1))
		c = c.add(max).add(1).sub(min)
	}

	fmt.Println(c)
}

type mint int64

var mod = mint(1e9 + 7)

// add は a + bを返します
func (a mint) add(b mint) mint {
	return (a + b) % mod
}

// sub は a - bを返します
func (a mint) sub(b mint) mint {
	return (a - b + mod) % mod
}

// mul は a * bを返します
func (a mint) mul(b mint) mint {
	return (a * (b % mod)) % mod
}

// div は a/bを返します
func (a mint) div(b mint) mint {
	return a.mul(b.inv())
}

// inv は aの逆元を返します
func (a mint) inv() mint {
	// 拡張ユークリッドの互除法
	b := mod
	u := mint(1)
	v := mint(0)
	for b > 0 {
		t := a / b
		a -= t * b
		a, b = b, a
		u -= t * v
		u, v = v, u
	}
	return (u + mod) % mod
}

// pow は a ^ bを返します
func (a mint) pow(b mint) mint {
	ans := mint(1)

	for b != 0 {
		if b&1 == 1 {
			ans = ans.mul(a)
		}
		a = a.mul(a)
		b = b >> 1
	}
	return ans
}

var stdin = initStdin()

func initStdin() *bufio.Scanner {
	bufsize := 1 * 1024 * 1024 // 1 MB
	var stdin = bufio.NewScanner(os.Stdin)
	stdin.Buffer(make([]byte, bufsize), bufsize)
	stdin.Split(bufio.ScanWords)
	return stdin
}

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

func nextBytes() []byte {
	stdin.Scan()
	return stdin.Bytes()
}

func nextInt() int {
	i, _ := strconv.Atoi(nextString())
	return i
}

func nextInt64() int64 {
	i, _ := strconv.ParseInt(nextString(), 10, 64)
	return i
}
//  [go]
package main

import (
	"fmt"
)

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

	ans := 0
	for i := k; i <= n + 1; i++ {
		// [n - i + 1, ... n]
		smax := i * (n - i + 1 + n) / 2
		// [0, ... i - 1]
		smin := i * (i - 1) / 2
		// fmt.Println(smax, smin)
		ans += smax - smin + 1
		ans %= int(1e9) + 7
	}

	fmt.Println(ans);
}
//  [ruby]
mod = 10 ** 9 + 7

n, k = gets.to_s.split.map{|e|e.to_i}

# ans = (k..n+1).map{|i| i * (n + n - i + 1) / 2 - i * ( i - 1 ) / 2 + 1 }.sum % mod

puts (n * (n+1) * (n+2) / 6 - k * (k-1) * (3*n-2*k+4) / 6 + (n - k + 2)) % mod
//  [ruby]
n, k = gets.split.map(&:to_i)

total = 0
(k..(n+1)).each do |i|
  total += i * (n - i + 1) + 1
end

puts total % (10**9+7)
//  [ruby]
mod = 10 ** 9 + 7

n, k = gets.to_s.split.map{|e|e.to_i}

# ans = (k..n+1).map{|i| i * (n + n - i + 1) / 2 - i * ( i - 1 ) / 2 + 1 }.sum % mod
ans = n - k + 2
(k..n+1).each do |i|
  
  ans += i * (n - i + 1) 
  #ans %= mod if ans >= mod
end

puts ans % mod
//  [ruby]
class Integer
  def value
    self.to_i
  end
end

class MInt < Numeric
  
  attr_reader :value, :mod
  @@mod = 10 ** 9 + 7
  @@h = Hash.new
  # delegate :to_i, :to_f, :to_s, to: :value
  
  def to_i
    @value
  end
  
  def initialize(value)
    @value = value
  end
  
  def +@
    MInt.new(value.to_i % @@mod)
  end

  def -@
    MInt.new(-value.to_i % @@mod)
  end
  
  def +(other)
    MInt.new((value + other.value.to_i) % @@mod)
  end
  
  def -(other)
    MInt.new((value - other.value.to_i) % @@mod)
  end
  
  def *(other)
    MInt.new((value * other.value.to_i) %@@mod)
  end
  
  def /(other)
    @@h[other.value] ||= other.value.to_i.pow(@@mod-2, @@mod)
    MInt.new(self.value.to_i * @@h[other.value.to_i])
  end
  
  def ==(other)
    ( value % @@mod ) == ( other.value % @@mod )
  end
  
  def abs
    value %= @@mod
    self 
  end
  
  def to_s
    (value % @@mod).to_s
  end
  
  def inspect
    (value % @@mod).to_s
  end
  
  def coerce(other)
    [MInt.new(other), self]
  end
end

# a = MInt.new(54)
# b = MInt.new(10**9+6)

# p  a + b
# p -b
# p MInt.new(54) + (10**9+6)

nn, kk = gets.to_s.split.map{|e|e.to_i}

n = MInt.new(nn)
k = MInt.new(kk)

ans = (kk..nn+1).map{|i| i * (n + n - i + 1) / 2 - i * ( i - 1 ) / 2 + 1 }.sum

puts ans
# puts ans % (10 ** 9 + 7)
//  [ruby]
class Integer
  
  attr_accessor :mod
  @@mod = 10 ** 9 + 7
  
  alias_method :primitive_add, :+
  def +(other)
    res = self.primitive_add(other)
    res %= @@mod if res < 0 || res >= @@mod
    res
  end
  
  alias_method :primitive_minus, :-
  def -(other)
    res = self.primitive_minus(other)
    res %= @@mod if res < 0 || res >= @@mod
    res
  end
  
  alias_method :primitive_times, :*
  def *(other)
    self.primitive_times(other) % @@mod
  end
  
  def /(other)
    self * other.pow(@@mod-2, @@mod) % @@mod
  end
end

n, k = gets.to_s.split.map{|e|e.to_i}

ans = (k..n+1).map{|i| i * (n + n - i + 1) / 2 - i * ( i - 1 ) / 2 + 1 }.reduce(:+)

puts ans
//  [ruby]
class Mint < Numeric
  
  attr_reader :value, :mod
  @@mod = 10 ** 9 + 7
  
  def initialize(value)
    @value = value
  end
  
  def +(other)
    if other.kind_of?(Mint)
      Mint.new((value + other.value) % @@mod)
    elsif other.kind_of?(Integer)
      Mint.new((value + other) % @@mod)
    else
      x, y = other.coerce(self)
      x + y
    end
  end
  
  def -(other)
    if other.kind_of?(Mint)
      Mint.new((value - other.value) % @@mod)
    elsif other.kind_of?(Integer)
      Mint.new((value - other) % @@mod)
    else
      x, y = other.coerce(self)
      x - y
    end
  end
  
  def *(other)
    if other.kind_of?(Mint)
      Mint.new((value * other.value) % @@mod)
    elsif other.kind_of?(Integer)
      Mint.new((value * other) % @@mod)
    else
      x, y = other.coerce(self)
      x * y
    end
  end
  
  def /(other)
    if other.kind_of?(Mint)
      Mint.new((value * other.value.pow(@@mod-2, @@mod) % @@mod ))
    elsif other.kind_of?(Integer)
      Mint.new((value * other.pow(@@mod-2, @@mod) % @@mod ))
    else
      x, y = other.coerce(self)
      x / y
    end
  end
  
  # def %(other)
  #   if other.kind_of?(Mint)
  #     raise MintDivisionError
  #   elsif other.kind_of?(Integer)
  #     Mint.new(value % @@mod)
  #   else
  #     x, y = other.coerce(self)
  #     x % y
  #   end
  # end
  
  def coerce(other)
    if other.kind_of?(Integer)
      return [Mint.new(other), self]
    elsif other.kind_of?(Mint)
      return [other, self]
    else
      super
    end
  end
  
  def inspect
    "#{value} (mod #{@@mod})"
  end
  
  def to_s
    "#{value % @@mod}"
  end
end

class Integer
  
  def coerce(other)
    if other.kind_of?(Mint)
      return [other, Mint.new(self)]
    elsif other.kind_of?(Integer)
      return [other, self]
    else
      super
    end
  end
  
end

class MintDivisionError < StandardError
  def initialize(msg="divided by Mint")
    super
  end
end

class Range
  alias_method :primitive_initialize, :initialize
  def initialize(s,t)
    s = s.value if s.kind_of?(Mint)
    t = t.value if s.kind_of?(Mint)
    primitive_initialize(s,t)
  end
end

n, k = gets.to_s.split.map{|e|e.to_i}
 
ans = (k..n+1).map{|i| Mint.new(i) * (n + n - i + 1) / 2 - i * ( i - 1 ) / 2 + 1 }.sum
 
puts ans
//  [rust]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let mut s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

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

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

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

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

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

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

    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}
fn myalloc(n: usize) -> Box<[f64]> {
    vec![0.0; n].into_boxed_slice()
}
fn main(){
    input!{n: i64,
    m: i64}
    let allcolum:i64 =n+1-m+1;
    let mut ans:i64=0;
    for i in 0 ..allcolum{
        ans+=(n-(m+i)+1)*(m+i)+1
    }
    println!("{}", ans%1000000007)
}
//  [rust]
#![allow(unused_imports)]
#![allow(unused_macros)]
#![allow(non_snake_case)]
#![allow(dead_code)]
#![allow(unused_variables)]
#![allow(unused_mut)]
#![allow(unused_assignments)]
use proconio::input;
use proconio::marker::Usize1;
use std::collections::*;
use std::cmp::*;
use std::f64::consts::*;

const MOD: i64 = 1000000007;
const INF: usize = std::usize::MAX / 4;

fn main() {
    input! {
        N: i64,
        K: i64,
    }

    let mut ans: i64 = 0;
    for k in K..N+2 {
        let mi = k * (k - 1) / 2;
        let mx = N * k - mi;
        ans += mx - mi + 1;
        ans %= MOD;
    }

    println!("{}", ans);
}
//  [rust]
use proconio::{input, fastout};

const MOD : i64 = 1e9 as i64 + 7;

#[fastout]
fn main() {
    input! {
        n : i64,
        k : i64
    }
    let mut ans : i64 = 0;
    for pick in k..=std::cmp::max(k, n + 1) {
        let smallest = (pick - 1) * pick / 2;
        let largest = (n - pick + 1) * pick + (pick - 1) * pick / 2;
        let range = largest - smallest + 1;
        ans += range;
        ans %= MOD;
    }
    println!("{}", ans);
}
//  [rust]
#![allow(unused_imports)]
#![allow(non_snake_case)]
#![allow(dead_code)]
#![allow(unused_macros)]
#![allow(unused_mut)]
use num::integer::gcd;
use proconio::fastout;
use proconio::input;
use proconio::marker::{Bytes, Chars};
use std::f64::consts::PI;
use std::mem::swap;

type Pi = (i32, i32);

fn pri<T: std::fmt::Display>(x: T) {
    println!("{}", x);
}

#[fastout]
fn main() {
    input! {
        n: u32, k:u32,
    }
    let mut ans = Mint(0);
    let mut sum = vec![Mint(0)];
    for i in 0..n + 1 {
        sum.push(Mint(i) * (Mint(i + 1)) * Mint(2).inv());
    }
    let n = n as usize;
    let k = k as usize;
    for i in k..n + 2 {
        ans += sum[n + 1] - sum[n + 1 - i] - sum[i] + Mint(1);
    }
    pri(ans);
}

// Modint
const MOD: u32 = 1_000_000_007;
#[derive(Clone, Copy)]
struct Mint(u32);
impl std::ops::Add for Mint {
    type Output = Mint;
    fn add(self, x: Mint) -> Mint {
        let res = self.0 + x.0;
        Mint(if res >= MOD { res - MOD } else { res })
    }
}
impl std::ops::AddAssign for Mint {
    fn add_assign(&mut self, x: Mint) {
        *self = *self + x;
    }
}
impl std::ops::Sub for Mint {
    type Output = Mint;
    fn sub(self, x: Mint) -> Mint {
        let res = self.0 + MOD - x.0;
        Mint(if res >= MOD { res - MOD } else { res })
    }
}
impl std::ops::SubAssign for Mint {
    fn sub_assign(&mut self, x: Mint) {
        *self = *self - x;
    }
}
impl std::ops::Mul for Mint {
    type Output = Mint;
    fn mul(self, x: Mint) -> Mint {
        Mint((self.0 as u64 * x.0 as u64 % MOD as u64) as u32)
    }
}
impl std::ops::MulAssign for Mint {
    fn mul_assign(&mut self, x: Mint) {
        *self = *self * x;
    }
}
impl std::ops::Div for Mint {
    type Output = Mint;
    fn div(self, x: Mint) -> Mint {
        let mut a = x.0 as i64; //solves au + mv = 1 and u = a^-1
        let mut m = MOD as i64;
        let mut u = 1i64;
        let mut v = 0i64;
        while m != 0 {
            let t = a / m;
            a -= t * m;
            swap(&mut a, &mut m);
            u -= t * v;
            swap(&mut u, &mut v);
        }
        u %= m;
        if u < 0 {
            u += m;
        }
        self * Mint(u as u32)
    }
}
impl std::ops::DivAssign for Mint {
    fn div_assign(&mut self, x: Mint) {
        *self = *self / x;
    }
}
impl std::fmt::Display for Mint {
    fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}
impl Mint {
    pub fn pow(self, mut n: u32) -> Mint {
        let mut res = Mint(1);
        let mut r = self;
        while n > 0 {
            if n & 1 == 1 {
                res *= r;
            }
            r *= r;
            n >>= 1;
        }
        res
    }
    pub fn inv(self) -> Mint {
        assert!(self.0 != 0);
        self.pow(MOD - 2)
    }
}
fn facinit(n: u32) -> Vec<Mint> {
    let mut res = Vec::new();
    let mut k = Mint(1);
    res.push(k);
    for i in 1..n + 1 {
        k *= Mint(i);
        res.push(k);
    }
    res
}
//  [swift]
protocol InitFromString {
    init?(_ str: String)
}

extension Int: InitFromString {}
extension Int8: InitFromString {}
extension Int16: InitFromString {}
extension Int32: InitFromString {}
extension Int64: InitFromString {}
extension String: InitFromString {}

func input<T: InitFromString>() -> [T] {
    readLine()!.split(separator: " ").map(String.init).compactMap(T.init)
}

let nk: [Int] = input()
let n = nk[0]
let k = nk[1]

let mod = 1000_000_000 + 7

let result = (k...(n+1)).reduce(0, { res, i in
    let max = sum((n-i+1)...n)
    let min = sum(0...(i - 1))
    return (res + max - min + 1) % mod
})

print(result == 0 ? 1 : result % mod)

func sum(_ arr: ClosedRange<Int>) -> Int {
    return (arr.first! + arr.last!) * arr.count / 2
}
//  [swift]
protocol InitFromString {
    init?(_ str: String)
}

extension Int: InitFromString {}
extension Int8: InitFromString {}
extension Int16: InitFromString {}
extension Int32: InitFromString {}
extension Int64: InitFromString {}
extension String: InitFromString {}

func input<T: InitFromString>() -> [T] {
    readLine()!.split(separator: " ").map(String.init).compactMap(T.init)
}

let nk: [Int] = input()
let n = nk[0]
let k = nk[1]

let mod = 1000_000_000 + 7

let result = (k...(n+1)).reduce(0, { res, i in
    let max = sum(a: n - i + 1, l: n, n: i)
    let min = sum(a: 0, l: i - 1, n: i)
    return (res + max - min + 1) % mod
})

print(result == 0 ? 1 : result % mod)

func sum(a: Int, l: Int, n: Int) -> Int {
    return n * (a + l) / 2
}
//  [swift]
// Sum of Large Numbers

func rangeSum(_ start: Int, _ end: Int) -> Int {
    let count = end - start + 1
    return (start + end) * count / 2
}

func combi(n: Int, k: Int) -> Int{
    let min = rangeSum(0, k-1)
    let max = rangeSum(n-k+1, n)
    return max - min + 1
}

func main() {
    let nk = readLine()!.split(separator: " ").map{Int($0)!}
    let n = nk[0]
    let k = nk[1]
    var sum = 0
    for i in k...(n+1) {
        sum += combi(n: n, k: i)
        while sum > 1000000007 {
            sum -= 1000000007
        }
    }
    print(sum)
}

main()
//  [swift]
let mod = 1000000007

let line = readLine()!.split(separator: " ").map({Int($0)!})
let N = line[0]
let K = line[1]
var ans = 0
for i in K...(N + 1) {
    ans += i * (N + 1 - i) + 1
    ans %= mod
}
print(ans)
//  [swift]
let mod = 1_000_000_007

let input = readLine()!.split(separator: " ").map { Int($0)! }
let N = input[0]
let K = input[1]

func sum(_ first: Int, _ last: Int, _ count: Int) -> Int {
    (first + last) * count / 2
}

var result = 0
for i in K ... N + 1 {
    let min = sum(0, i - 1, i)
    let max = sum(N - i + 1, N, i)
    result += max - min + 1
    result %= mod
}

print(result)
//  [typescript]
export class Main {
  static main(input: string): string {
    const mod = Math.pow(10, 9) + 7;
    const tmp: string[] = input.split("\n");
    const [n, k]: number[] = tmp.shift().split(" ").map(int => parseInt(int));
    let min = ((k - 2) * (k - 1) / 2) % mod;
    let max = ((n + (n - (k - 2))) * (k - 1) / 2) % mod;
    let result = 0;
    for (let i = k, len = n + 1; i <= len; i++) {
      min = (min + (i - 1)) % mod;
      max = (max + (n - (i - 1))) % mod;
      let t = max - min + 1;
      let diff = t < 0 ? mod + t : t;
      result = (result + diff) % mod;
    }
    return `${result}`;
  }
}
console.log(Main.main(require("fs").readFileSync("/dev/stdin", "utf8")));
//  [typescript]
import { count } from 'console';

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 n = Number(inputs[0].split(' ')[0]);
  const k = Number(inputs[0].split(' ')[1]);
  const pom = Math.pow(10, 9) + 7;

  let min = calc(k - 1, 0);
  let max = calc(n, n - (k - 1));
  let ans = max - min + 1;

  for (let i = k; i < n + 1; i++) {
    min += i;
    max += n - i;

    ans += max - min + 1;
  }

  console.log(ans % pom);
}

function calc(num: number, min: number): number {
  let sum = 0;
  while (num >= min) {
    sum += num;
    num--;
  }

  return sum;
}
//  [typescript]
import * as fs from 'fs'

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

const [n, k] = args[0].map(x => parseInt(x));

const P = 1000000007;

let tmp = 0;
for (let i = k; i <= n + 1; i++) {
  let max = Math.floor(((n - i + 1) + n) * i / 2);
  let min = Math.floor((0 + (i - 1)) * i / 2);
  tmp = (tmp + (max - min + 1) % P) % P;
}

console.log(tmp);
//  [python]
def reduce(arr,n):
    count=len(arr)*(len(arr)-1)*(n-len(arr))/2+len(arr)*(len(arr)-1)*(len(arr)-2)/6
    return count

n=int(input())
s=input()

r,g,b=[],[],[]

for i,j in enumerate(s):
    if j=='R':
        r.append(i)
    elif j=='G':
        g.append(i)
    else:
        b.append(i)

count= n*(n-1)*(n-2)/6
count-=reduce(r,n)
count-=reduce(g,n)
count-=reduce(b,n)

for i in range(n):
    for j in range(i+1,n):
        if j+(j-i)<n:
            if s[i]!=s[j] and s[j]!=s[j+(j-i)] and s[i]!=s[j+(j-i)]:
                count-=1
print(int(count))
//  [python]
N=int(input())
T=input()
S=[0 for _ in range(N)]
for i in range(N):
  if T[i]=='G':
    S[i]=1
  elif T[i]=='B':
    S[i]=2
    
ls=[(0,0,0) for _ in range(N)]
for i in range(N):
  if S[i]==0:
    ls[i]=(ls[i-1][0]+1,ls[i-1][1],ls[i-1][2])
  elif S[i]==1:
    ls[i]=(ls[i-1][0],ls[i-1][1]+1,ls[i-1][2])
  else:
    ls[i]=(ls[i-1][0],ls[i-1][1],ls[i-1][2]+1)


def count(x):
  val=0
  y=(x+1)%3
  z=(x+2)%3
  for i in range(N):
    if S[i]==x:
      for j in range(i+1,N):
        if S[j]==y:
          val+=ls[N-1][z]-ls[j][z]
          if 2*j-i<N and S[2*j-i]==z:
            val-=1
        if S[j]==z:
          val+=ls[N-1][y]-ls[j][y]
          if 2*j-i<N and S[2*j-i]==y:
            val-=1
  return val

print(count(0)+count(1)+count(2))
//  [python]
N = int(input())
S = input()
R = 0
B = 0
G = 0
for i in range(N):
    if S[i] == 'R':
        R += 1
    elif S[i] == 'G':
        G += 1
    else:
        B += 1
ans = R*G*B
for i in range(N):
    for j in range(i+1,N):
        k = 2*j-i
        if k >= N:
            continue
        elif S[i]!= S[j] and S[i] != S[k] and S[j] != S[k]:
            ans -= 1

print(ans)
//  [java]
import java.util.Scanner;

public class Main{
  public static void main(String[] args){
	  Scanner sc = new Scanner(System.in);
	  int n=sc.nextInt(),rm=0,gm=0,bm=0;
	  long count=0,buff=0;
	  String s=sc.next();
	  int[] r=new int[s.length()],g=new int[s.length()],b=new int[s.length()];
	  for(int i=0;i<s.length();i++) {
		  if(s.substring(i, i+1).equals("R"))rm++;
		  if(s.substring(i, i+1).equals("G"))gm++;
		  if(s.substring(i, i+1).equals("B"))bm++;
	  }
	  for(int i=0;i<s.length();i++) {
		  r[i]=rm;
		  g[i]=gm;
		  b[i]=bm;
		  if(s.substring(i, i+1).equals("R"))rm--;
		  if(s.substring(i, i+1).equals("G"))gm--;
		  if(s.substring(i, i+1).equals("B"))bm--;
	  }
	  for(int i=0;i<s.length()-1;i++) {
		  for(int j=i+1;j<s.length();j++) {
			  if(!s.substring(i, i+1).equals(s.substring(j, j+1))) {
				  if(2*j-i+1<=s.length()) {
					  if(!s.substring(2*j-i,2*j-i+1).equals(s.substring(i, i+1)) && !s.substring(2*j-i,2*j-i+1).equals(s.substring(j, j+1))) {
						  buff++;
					  }
				  }
			  }
		  }
	  }
	  boolean R=true,G=true,B=true;
	  for(int i=0;i<s.length()-2;i++) {
		  for(int j=i+1;j<s.length()-1;j++) {
			  if(s.substring(i, i+1).equals(s.substring(j, j+1)))continue;
			  else {
				  if(s.substring(i, i+1).equals("R"))R=false;
				  if(s.substring(i, i+1).equals("G"))G=false;
				  if(s.substring(i, i+1).equals("B"))B=false;
				  if(s.substring(j, j+1).equals("R"))R=false;
				  if(s.substring(j, j+1).equals("G"))G=false;
				  if(s.substring(j, j+1).equals("B"))B=false;
				  if(R) {
					  count+=r[j+1];
				  }else if(G) {
					  count+=g[j+1];
				  }else if(B) {
					  count+=b[j+1];
				  }
			  }
			  R=true;
			  G=true;
			  B=true;
			//System.out.println(count);
		  }
	  }
	  /*System.out.println(Arrays.toString(r));
	  System.out.println(Arrays.toString(g));
	  System.out.println(Arrays.toString(b));*/
	  System.out.println(count-buff);
  }
}
//  [cpp]
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#define NMAX 4002
using namespace std;
int main(){
  long long N,ans = 0;
  char S[NMAX];
  vector<int> v[3];
  cin >> N;
  for (int i = 0; i < N; ++i)
  {
    cin >> S[i];
    if(S[i] == 'R') v[0].push_back(i);
    else if(S[i] == 'G') v[1].push_back(i);
    else if(S[i] == 'B') v[2].push_back(i);
  }
  for (int i = 0; i < v[0].size(); ++i)
  {
    for (int j = 0; j < v[1].size(); ++j)
    {
      int num = 0;
      if(find(v[2].begin(), v[2].end(),(v[0][i]*2-v[1][j])) != v[2].end()) num++;
      if(find(v[2].begin(), v[2].end(),(v[1][j]*2-v[0][i])) != v[2].end()) num++;
      if(find(v[2].begin(), v[2].end(),(v[0][i]+v[1][j])/2) != v[2].end() && (v[0][i]+v[1][j])%2 == 0) num++;
      ans += v[2].size() - num;
    }
  }
  cout << ans << endl;

}
//  [cpp]
#include <iostream>
#include <string>
#include <algorithm>
#include <functional>
#include <vector>
#include <stack>
#include <queue>
#include <deque>
#include <set>
#include <map>
#include <cstdio>
#include <cmath>
#include <tuple>
#include <iomanip>
#include <numeric>
#include <unordered_map>
#include <sstream>   
#include<limits.h>
#include<float.h>
#include<list>
#include <array>
#include <complex>
#include<stdio.h>
#include<string.h>
#include <bitset>

using namespace std;
#define int  long long
 
#define I32_MAX 2147483647
#define I64_MAX 9223372036854775807LL
#define I64_MAX2 1223372036854775807LL
#define INF I64_MAX2
#define MOD 1000000007
#define MEM_SIZE 10000
#define DEBUG_OUT true
#define ALL(x) (x).begin(),(x).end()

// int DP[MEM_SIZE][MEM_SIZE] = {0};
// int GMEM[MEM_SIZE][MEM_SIZE] = {0};
template<typename T> void DEBUG(T e){if(DEBUG_OUT == false)return; std::cout << e <<" ";}
template<typename T> void DEBUG(const std::vector<T>& v){if(DEBUG_OUT == false)return;for(const auto& e : v){std::cout<< e << " "; } std::cout << std::endl;}
template<typename T> void DEBUG(const std::vector<std::vector<T> >& vv){if(DEBUG_OUT == false)return;for(const auto& v : vv){ DEBUG(v); } }
template<class T,class... Ts> void DEBUG(T d, Ts... e){if(DEBUG_OUT == false)return;DEBUG(d);DEBUG(e...);};
template <class T> void corner(bool flg, T hoge) {if (flg) {cout << hoge << endl; exit(0);}}
template< typename T1, typename T2 > inline bool chmax(T1 &a, T2 b) { return a < b && (a = b, true); }
template< typename T1, typename T2 > inline bool chmin(T1 &a, T2 b) { return a > b && (a = b, true); }


//FUNCTION
void solve(void)
{
  int N;
  cin>>N;
  string str;
  cin>>str;
  vector<int> R,G,B;
  for (int i = 0; i < N; i++)
  {
    if(str[i] =='R')
    {
      R.push_back(i);
    }
    else if(str[i] =='G')
    {
      G.push_back(i);
    }
    else
    {
      B.push_back(i);
    }
  }
  int ANS = R.size()*G.size()*B.size();
  for (int i = 0; i < R.size(); i++)
  {
    for (int j = 0; j < G.size(); j++)
    {
       int P = R[i]; int Q = G[j];
       if(P > Q) swap(P,Q);
       if(find(ALL(B),P - abs(Q - P)) != B.end())
       {
         ANS--;
       }
       if(find(ALL(B),Q + abs(Q - P)) != B.end())
       {
         ANS--;
       }
       if(find(ALL(B),(P+Q)/2) != B.end() && (P+Q)%2 == 0)
       {
         ANS--;
       }
      //  DEBUG(P,Q, P + abs(Q - P));
    }
    
  }
  // DEBUG(R);DEBUG(G);DEBUG(B);
  cout<<ANS<<endl;
  
  
  
  return;
}

int32_t main(int32_t argc, const char *argv[])
{
  std::ios::sync_with_stdio(false);
  std::cin.tie(0);

  std::cout << std::fixed;
  std::cout << std::setprecision(15);
  solve();

  return 0;
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> P;

#define repr(i, n) for(int i = n; i >= 0; i--)
#define reprl(i, n) for(ll i = n; i >= 0; i--)
#define all(v) v.begin(), v.end()
ll gcd(ll a,ll b) {
  return b? gcd(b,a%b): a;  
}
ll lcm(ll a,ll b) {
  return a*b/gcd(a,b);
}
bool isLowerCase(char c){
  return (c>='a'&&c<='z');
}
const string outputYesNo(bool ans){
  return (ans?"Yes":"No");
}
int main() {
  int n;cin>>n;
  string s;cin>>s;
  string rgb="RGB";
  map<char,vector<int>> mrgb;
  ll ans=0;
  for(int i=0;i<n;i++){
    mrgb[s[i]].push_back(i);
  }
  vector<int> &r=mrgb['R'];
  vector<int> &g=mrgb['G'];
  vector<int> &b=mrgb['B'];
  ans=r.size()*g.size()*b.size();
  for(int i=0;i<r.size();i++){
    for(int j=0;j<g.size();j++){
      int l,s;
      if(r[i]<g[j]){
        l=g[j];
        s=r[i];
      }else{
        l=r[i];
        s=g[j];
      }
      int ng=s-(l-s);
      if(find(all(b),ng)!=b.end()){
        ans--;
      }
      ng=(s+l)/2;
      if(find(all(b),ng)!=b.end()){
        if((s+l)%2==0){
          ans--;
        }
      }
      ng=l+(l-s);
      if(find(all(b),ng)!=b.end()){
        ans--;
      }
    }
  }
  cout<<ans<<endl;
  return 0;
}
//  [c]
#include <stdio.h>
typedef unsigned long long int llu;

int main(void) {
  llu s = 0;
  int n, r[4000], g[4000], b[4000], rl = 0, gl = 0, bl = 0, fi, si, ti, d;
  char c;
  scanf("%d\n", &n);
  for (int i = 0; i < n; i++) {
    scanf("%c", &c);
    if (c == 'R') {
      r[rl] = i;
      rl++;
    } else if (c == 'G') {
      g[gl] = i;
      gl++;
    } else {
      b[bl] = i;
      bl++;
    }
  }

  fi = 0;
  si = 0;
  for (int i = 0; i < rl; i++) {
    ti = 0;
    for (int j = fi; j < gl; j++) {
      if (g[j] < r[i]) {
        fi = j;
        continue;
      }
      d = g[j] - r[i];
      for (int k = ti; k < bl; k++) {
        if (b[k] < g[j]) {
          ti = k;
          continue;
        }
        if (b[k] - g[j] != d) {
          s++;
        }
      }
    }
    ti = 0;
    for (int j = si; j < bl; j++) {
      if (b[j] < r[i]) {
        si = j;
        continue;
      }
      d = b[j] - r[i];
      for (int k = ti; k < gl; k++) {
        if (g[k] < b[j]) {
          ti = k;
          continue;
        }
        if (g[k] - b[j] != d) {
          s++;
        }
      }
    }
  }

  fi = 0;
  si = 0;
  for (int i = 0; i < gl; i++) {
    ti = 0;
    for (int j = fi; j < rl; j++) {
      if (r[j] < g[i]) {
        fi = j;
        continue;
      }
      d = r[j] - g[i];
      for (int k = ti; k < bl; k++) {
        if (b[k] < r[j]) {
          ti = k;
          continue;
        }
        if (b[k] - r[j] != d) {
          s++;
        }
      }
    }
    ti = 0;
    for (int j = si; j < bl; j++) {
      if (b[j] < g[i]) {
        si = j;
        continue;
      }
      d = b[j] - g[i];
      for (int k = ti; k < rl; k++) {
        if (r[k] < b[j]) {
          ti = k;
          continue;
        }
        if (r[k] - b[j] != d) {
          s++;
        }
      }
    }
  }

  fi = 0;
  si = 0;
  for (int i = 0; i < bl; i++) {
    ti = 0;
    for (int j = fi; j < rl; j++) {
      if (r[j] < b[i]) {
        fi = j;
        continue;
      }
      d = r[j] - b[i];
      for (int k = ti; k < gl; k++) {
        if (g[k] < r[j]) {
          ti = k;
          continue;
        }
        if (g[k] - r[j] != d) {
          s++;
        }
      }
    }
    ti = 0;
    for (int j = si; j < gl; j++) {
      if (g[j] < b[i]) {
        si = j;
        continue;
      }
      d = g[j] - b[i];
      for (int k = ti; k < rl; k++) {
        if (r[k] < g[j]) {
          ti = k;
          continue;
        }
        if (r[k] - g[j] != d) {
          s++;
        }
      }
    }
  }

  printf("%llu\n", s);
}
//  [c]
#include <stdio.h>

long count(int x[], int nx, int y[], int ny, int z[], int nz) {
   int i,j,k,jj,kk,l;
   long a;

   a=jj=kk=0;
   for (i=0;i<nx;i++) {
       for (j=jj;j<ny;j++)
          if (y[j]>x[i]) break;
       if (j==ny) continue;
       jj=j;
       for (k=kk;k<nz;k++)
          if (z[k]>x[i]) break;
       if (k==nz) continue;
       kk=k;
       for (;j<ny && k<nz;)
          if (y[j]<z[k]) {
             for (l=k;l<nz;l++)
                if (y[j]-x[i]!=z[l]-y[j]) a++;
             j++;
          } else {
             for (l=j;l<ny;l++)
                if (z[k]-x[i]!=y[l]-z[k]) a++;
             k++;
          }
   }
   return a;
}

int main(){
   int i,n,r[4000],g[4000],b[4000],rp,gp,bp;
   char s[4001];
   long sum;

   scanf("%d",&n);
   scanf("%s",s);
   rp=gp=bp=0;
   for (i=0;i<n;i++)
      if (s[i]=='R') r[rp++]=i;
      else if (s[i]=='G') g[gp++]=i;
      else b[bp++]=i;
   sum=count(r,rp,g,gp,b,bp);
   sum+=count(g,gp,r,rp,b,bp);
   sum+=count(b,bp,g,gp,r,rp);
   printf("%ld\n",sum);
   return 0;
}
//  [c]
#include <stdio.h>
int main(){
  int n,i,j,k,t;
  unsigned int ans=0;
  scanf("%d\n",&n);
  int a[n],b[n],c[n],ac=0,bc=0,cc=0;
  char s[n];
  scanf("%s",s);
  for(i=0;i<n;i++){
    if(s[i]=='R'){
      a[ac]=i;
      ac++;
    }
    else if(s[i]=='G'){
      b[bc]=i;
      bc++;
    }
    else{
      c[cc]=i;
      cc++;
    }
  }
  for(i=0;i<ac;i++){
    for(j=0;j<bc;j++){
      for(k=0;k<cc;k++){
        t=a[i]+b[j]+c[k];
        if(t!=3*a[i]){
          if(t!=3*b[j]){
            if(t!=3*c[k]){
              ans++;
            }
          }
        }
      }
    }
  }
  printf("%lu",ans);
  return 0;
}
//  [javascript]
"use strict";
function main(input) {
  const n = parseInt(input[0]);
  const s = input[1].trim().split("");
  const rgb = { "R":0, "G":0, "B":0 };

  for(let i of s){
    rgb[i]++;
  }

  let sum = rgb.R * rgb.G * rgb.B;

  for(let i=1;i<n;i++){
    for(let j=i;j<=n-i;j++){
      let checker = [s[j-i], s[j], s[j+i]].sort(); 
      if(checker.join("") === "BGR"){
        sum--;
      }
    }
  }
  console.log(sum);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8').trim().split("\n"));
//  [javascript]
function Main(input){
	input = input.split("\n");
	var arr = input[1].split("");
	var n = input[0]-0;
	var rgb = [0,0,0];
	for(var i=0;i<arr.length;i++){
		switch(arr[i]){
			case "R":
			rgb[0]++;
			break;
			case "G":
			rgb[1]++;
			break;
			case "B":
			rgb[2]++;
			break;
		}
	}
	var sum = rgb[0]*rgb[1]*rgb[2];

	for(i=1;i<=n;i++){
		for(var j=i;j<arr.length-i+1;j++){
			var p = [];
			p.push(arr[j]);
			p.push(arr[j-i]);
		    p.push(arr[j+i]);
		    p=p.sort();
		    //console.log(p)
			if(p[0]=="B"&&p[1]=="G"&&p[2]=="R") sum--;
		}
	}
	console.log(sum);
}Main(require("fs").readFileSync("/dev/stdin", "utf8").trim());
//  [javascript]
function Main(input) {
  input = input.trim().split("\n").map(function(x) { return x.split(" ")});
  var N = parseInt(input[0],10);
  var S = input[1][0];
  var vec_R = Array.from({length: N + 1}, () => 0);
  var vec_G = Array.from({length: N + 1}, () => 0);
  var vec_B = Array.from({length: N + 1}, () => 0);
  var arr_chr = [vec_R,vec_G,vec_B];
  var ans = 0;
  for(var i = S.length - 1; i >= 0; i--){
    if(S.substr(i, 1) === 'R') {
      vec_R[i] = vec_R[i + 1] + 1;
      vec_G[i] = vec_G[i + 1];
      vec_B[i] = vec_B[i + 1]; 
    }
    if(S.substr(i, 1) === 'G') {
      vec_R[i] = vec_R[i + 1];
      vec_G[i] = vec_G[i + 1] + 1;
      vec_B[i] = vec_B[i + 1];
    }
    if(S.substr(i, 1) === 'B') {
      vec_R[i] = vec_R[i + 1];
      vec_G[i] = vec_G[i + 1];
      vec_B[i] = vec_B[i + 1] + 1;
    }
  }
  vec_R = vec_R.pop();
  vec_G = vec_G.pop();
  vec_B = vec_B.pop();
  var a, b, c;
  var tmp = 0;
  for (var i = 0; i < (S.length - 3); i++){
    a = S.substr(i, 1);
    for (var j = i + 1; j < (S.length - 1); j++){
      b = S.substr(j, 1);
      if (a !== b){
        ans += arr_chr[chrSk_i(S, a, b)][j + 1];
        if (j+(j-i) < N && S.substr(j+(j-i), 1) !== a && S.substr(j+(j-i), 1) !== b) {
          ans --;
          tmp ++;
        }
      }
    }
  }
  function chrSk_i(S, a, b){
    if (a !== 'R' && b !== 'R') return 0;
    if (a !== 'G' && b !== 'G') return 1;
    if (a !== 'B' && b !== 'B') return 2;
  }
  console.log(ans);
}   

Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [go]
package main

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

var sc = bufio.NewScanner(os.Stdin)

func scanInt() int {
	num, _ := strconv.Atoi(scanString())
	return num
}

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

func init() {
	sc.Split(bufio.ScanWords)
}

func main() {
	l := scanInt()
	s := scanString()
	cnt := 0
	for i := 0; i < l; i++ {
		for j := i + 1; j < l; j++ {
			if s[i] == s[j] {
				continue
			}
			k := strings.Replace("RGB", string(s[i]), "", 1)
			k = strings.Replace(k, string(s[j]), "", 1)
			cnt += strings.Count(s[j+1:], k)
			if (2*j-i) <= (l-1) && k == string(s[2*j-i]) {
				cnt--
			}
		}
	}
	fmt.Println(cnt)
}
//  [go]
package main

import (
	"fmt"
	"sort"
)

func main() {
	var n int
	var s string
	fmt.Scan(&n, &s)
	r := make([]int, 0, n)
	g := make([]int, 0, n)
	b := make([]int, 0, n)
	for i := 0; i < n; i++ {
		if s[i] == 'R' {
			r = append(r, i+1)

		} else if s[i] == 'G' {
			g = append(g, i+1)

		} else {
			b = append(b, i+1)
		}
	}

	ans := 0
	ans += f(r, g, b)
	ans += f(r, b, g)
	ans += f(g, r, b)
	ans += f(g, b, r)
	ans += f(b, r, g)
	ans += f(b, g, r)
	fmt.Println(ans)
}

func f(r, g, b []int) int {
	ret := 0
	for i := 0; i < len(r); i++ {
		for j := 0; j < len(g); j++ {
			if r[i] >= g[j] {
				continue
			}
			ret += len(b) - sort.Search(len(b), func(k int) bool { return b[k] > g[j] })
			same := sort.Search(len(b), func(k int) bool { return b[k] >= g[j]+g[j]-r[i] })
			if same < len(b) && b[same] == g[j]+g[j]-r[i] {
				ret -= 1
			}
		}
	}
	return ret
}
//  [go]
package main

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

func main() {
	io := NewIo(os.Stdin, os.Stdout)
	defer io.Flush()
	_ = io.NextInt()
	s := io.Next()
	r, g, b := []int{}, []int{}, []int{}
	for i := range s {
		switch s[i] {
		case 'R':
			r = append(r, i)
		case 'G':
			g = append(g, i)
		case 'B':
			b = append(b, i)
		}
	}
	//logger.Println(r, g, b)
	ans := len(r) * len(g) * len(b)
	ans -= find(r, g, b) + find(r, b, g) + find(g, r, b) + find(g, b, r) + find(b, r, g) + find(b, g, r)
	io.Println(ans)
}

func find(a, b, c []int) (found int) {
	for i := 0; i < len(a); i++ {
		jBegin := sort.Search(len(b), func(j int) bool { return b[j] > a[i] })
		for j := jBegin; j < len(b); j++ {
			kBegin := sort.Search(len(c), func(k int) bool { return c[k] > b[j] })
			k := sort.Search(len(c[kBegin:]), func(k int) bool { return a[i]-2*b[j]+c[kBegin:][k] >= 0 })
			if k < len(c[kBegin:]) && a[i]-2*b[j]+c[kBegin:][k] == 0 {
				found++
			}
		}
	}
	return found
}

// Io is I/O object
type Io struct {
	reader    *bufio.Reader
	writer    *bufio.Writer
	tokens    []string
	nextToken int
}

// NewIo returns a new Io instance
func NewIo(r io.Reader, w io.Writer) *Io {
	return &Io{
		reader: bufio.NewReader(r),
		writer: bufio.NewWriter(w),
	}
}

// Flush flushes writer
func (io *Io) Flush() {
	err := io.writer.Flush()
	if err != nil {
		panic(err)
	}
}

// NextLine scans a line from stdin
func (io *Io) NextLine() string {
	var buffer []byte
	for {
		line, isPrefix, err := io.reader.ReadLine()
		if err != nil {
			panic(err)
		}
		buffer = append(buffer, line...)
		if !isPrefix {
			break
		}
	}
	return string(buffer)
}

// Next return a word from stdin
func (io *Io) Next() string {
	for io.nextToken >= len(io.tokens) {
		line := io.NextLine()
		io.tokens = strings.Fields(line)
		io.nextToken = 0
	}
	r := io.tokens[io.nextToken]
	io.nextToken++
	return r
}

// NextInt returns an integer from stdin
func (io *Io) NextInt() int {
	i, err := strconv.Atoi(io.Next())
	if err != nil {
		panic(err)
	}
	return i
}

// Println is a wrapper of fmt.Fprintln
func (io *Io) Println(a ...interface{}) {
	fmt.Fprintln(io.writer, a...)
}
//  [ruby]
n = gets.to_s.to_i
s = gets.to_s.chomp

h = Hash.new(0)
s.each_char do |c|
  h[c] += 1
end

ans = h['R']* h['G'] * h['B']
n.times do |j|
  
  (1...n).each do |t|
    i = j - t
    k = j + t
    break if i < 0 || n - 1 < k
    ans -= 1 if s[i] != s[j] && s[j] != s[k] && s[k] != s[i]
  end
end

puts ans
//  [ruby]
n = gets.to_i
s = gets

sum = s.count('R') * s.count('G') * s.count('B')

0.upto(n-1) do |i|
  (i+1).upto(n-1) do |j|
    k = j*2 - i
    next if (j >= k || n <= k || s[i] == s[j] || s[j] == s[k] || s[k] == s[i])
    
    sum -= 1
  end
end

puts sum
//  [ruby]
n = gets.to_s.to_i
s = gets.to_s.chomp

a = Array.new(3){0}
s.each_char do |c|
  a[c.ord%3] += 1
end

ans = a[0] * a[1] * a[2]
n.times do |j|
  
  (1...n).each do |t|
    i = j - t
    k = j + t
    break if i < 0 || n - 1 < k
    ans -= 1 if s[i] != s[j] && s[j] != s[k] && s[k] != s[i]
  end
end

puts ans
//  [rust]
use proconio::input;

fn main() {
  input! {
    _N: usize,
    S: String
  }
  
  let mut rs: Vec<usize> = vec![];
  let mut gs: Vec<usize> = vec![];
  let mut bs: Vec<usize> = vec![];
  
  for (i, c) in S.chars().enumerate() {
    match c {
      'R' => rs.push(i+1),
      'G' => gs.push(i+1),
      'B' => bs.push(i+1),
      _ => unreachable!()
    }
  }
  rs.reverse();
  gs.reverse();
  bs.reverse();
  
  let mut result = 0;
  result += culc(&mut rs, &mut gs, &mut bs);
  result += culc(&mut rs, &mut bs, &mut gs);
  result += culc(&mut bs, &mut rs, &mut gs);
  result += culc(&mut bs, &mut gs, &mut rs);
  result += culc(&mut gs, &mut rs, &mut bs);
  result += culc(&mut gs, &mut bs, &mut rs);
  
  println!("{}", result);
}

fn culc(r: &mut Vec<usize>, g: &mut Vec<usize>, b: &mut Vec<usize>) -> usize {
  let mut result = 0;
  for i in r.iter() {
    for j in g.iter() {
      if j < i { break }
      for k in b.iter() {
        if k < j { break }
        if i + k != j * 2 {
          result += 1;
        }
      }
    }
  }
  result
}
//  [rust]
#![allow(unused_imports)]
#![allow(unused_variables)]

use itertools::Itertools;
use maplit::hashmap;
use proconio::marker::*;
use proconio::*;

#[fastout]
fn main() {
    input! {
        n: usize,
        s: String,
    }
    // annotate for rust-analyzer
    let n: usize = n;
    let s: String = s;
    let c = s.chars().collect_vec();

    let mut table = vec![hashmap! {'R'=> 0, 'G'=> 0, 'B'=> 0}; n];
    let mut ans = 0u64;
    for i in 0..n {
        if i != 0 {
            table[i] = table[i - 1].clone();
        }
        *table[i].entry(c[i]).or_default() += 1;
    }
    //println!("{:?}", table);
    for i in 0..n - 2 {
        for j in i + 1..n - 1 {
            if c[i] == c[j] {
                continue;
            }
            //println!("{}{}", i, j);
            let cc = "RGB"
                .replace(c[i], "")
                .replace(c[j], "")
                .chars()
                .next()
                .unwrap();
            let ex = j + j - i;
            ans += if ex > n - 1 {
                table[n - 1][&cc] - table[j][&cc]
            } else {
                table[n - 1][&cc] - table[j][&cc] - (table[ex][&cc] - table[ex - 1][&cc])
            };
        }
    }

    println!("{}", ans);
}
//  [swift]
func main() {
    let N = Int(readLine()!)!
    let S = Array(readLine()!)
    
    var count: [Character: Int] = ["R": 0, "G": 0, "B": 0]
    for c in S {
        count[c]! += 1
    }
    
    var ans = 1
    for c in "RGB" {
        ans *= count[c]!
    }
    
    let rgb: Set<Character> = ["R", "G", "B"]
    for i in 1...((N - 1) / 2) {
        var first = 0
        while first + 2 * i < N {
            let mid = first + i
            let last = first + 2 * i
            if rgb.isSubset(of: [S[first], S[mid], S[last]]) {
                ans -= 1
            }
            first += 1
        }
    }
    
    print(ans)
}

main()
//  [swift]
import Foundation

let N = Int(readLine()!)!
let S = [Character](readLine()!)
var r=0,g=0,b=0,rg=0,gb=0,br=0,rgb=0
for i in 0..<N {
  if S[i] == "R" { r += 1; rg += g; br += b; rgb += gb }
  else if S[i] == "G" { g += 1; rg += r; gb += b; rgb += br }
  else if S[i] == "B" { b += 1; gb += g; br += r; rgb += rg }
}
outerLoop: for i in 0..<N-2 {
  innerLoop: for j in i+1..<N-1 {
    var k = 2 * j - i
    if k >= N { break innerLoop }
    var s = Set<Character>([S[i], S[j], S[k]])
    if s.count == 3 { rgb -= 1 }
  }
}
print(rgb)
//  [typescript]
import { readFileSync } from "fs";

export const solveD = (n: number, s: string): number => {
  type RGB = "R" | "G" | "B";
  const rgb: { [k in RGB]: number } = { R: 0, G: 0, B: 0 };
  const r: number[] = [];
  const g: number[] = [];
  const b: number[] = [];
  for (let i = n - 1; i >= 0; i--) {
    rgb[s[i] as RGB]++;
    r[i] = rgb.R;
    g[i] = rgb.G;
    b[i] = rgb.B;
  }
  let comb = 0;
  const arr = (...a: RGB[]): number[] => {
    if (a.includes("R") && a.includes("G")) return b;
    if (a.includes("R") && a.includes("B")) return g;
    if (a.includes("G") && a.includes("B")) return r;
    return [];
  };
  for (let i = 0; i < n - 3; i++) {
    for (let j = i + 1; j < n - 1; j++) {
      if (s[i] === s[j]) continue;
      const ar = arr(s[i] as RGB, s[j] as RGB);
      const v =
        s[2 * j - i] && s[2 * j - i] !== s[i] && s[2 * j - i] !== s[j]
          ? ar[j + 1] - 1
          : ar[j + 1];
      comb += v;
    }
  }
  return comb;
};

if (require.main === module) {
  const [n, s] = readFileSync("/dev/stdin", "utf8").split("\n");
  console.log(solveD(+n, s));
}
//  [typescript]
import * as fs from "fs";

const input = (fs.readFileSync("/dev/stdin", "utf8") as string).split("\n");
const n = +input[0];
const s = input[1];

const rsw_r = { R: new Array(n + 1), G: new Array(n + 1), B: new Array(n + 1) };
rsw_r["R"][n] = rsw_r["G"][n] = rsw_r["B"][n] = 0;
for (let i = n - 1; i >= 0; i--) {
	rsw_r["R"][i] = rsw_r["R"][i + 1];
	rsw_r["G"][i] = rsw_r["G"][i + 1];
	rsw_r["B"][i] = rsw_r["B"][i + 1];
	rsw_r[s[i] as "R" | "G" | "B"][i]++;
}

const patterns = ["RGB", "RBG", "GBR", "GRB", "BRG", "BGR"];

let result = 0;
for (const pt of patterns) {
	for (let i = 0; i < n; i++) {
		if (s[i] !== pt[0]) continue;
		for (let d = 1; i + d < n; d++) {
			if (s[i + d] !== pt[1]) continue;
			result += rsw_r[pt[2] as "R" | "G" | "B"][i + d];
			if (i + d + d < n && s[i + d + d] === pt[2]) result--;
		}
	}
}
console.log(result)
//  [typescript]
class NormalInput {
  input: string[];
  pointer: number;
  constructor(raw: string) {
    this.input = raw.split(/ |\n/);
    this.pointer = 0;
  }
  int = (): number => {
    const ret = parseInt(this.input[this.pointer], 10);
    this.pointer++;
    return ret;
  };
  str = (): string => {
    const ret = this.input[this.pointer];
    this.pointer++;
    return ret;
  };
  strs = (length: number): string[] => {
    let ret: string[] = [];
    for (let i = 0; i < length; i++) {
      ret.push(this.str());
    }
    return ret;
  };
  ints = (length: number): number[] => {
    let ret: number[] = [];
    for (let i = 0; i < length; i++) {
      ret.push(this.int());
    }
    return ret;
  };
}
function rep(a: number, b: number) {
  let arr = [];
  for (let i = a; i < b; i++) arr.push(i);
  return arr;
}
function Main({ int, str, strs, ints }: NormalInput) {
  const N = int();
  const S = str();
  const total = Array.from(S).reduce(
    ([r, g, b], c) => [
      r + (c === "R" ? 1 : 0),
      g + (c === "G" ? 1 : 0),
      b + (c === "B" ? 1 : 0),
    ],
    [0, 0, 0]
  );

  const first = total[0] * total[1] * total[2];
  let second = 0;
  rep(0, N).forEach((i) =>
    rep(i + 2, N).forEach((k) => {
      if ((i + k) % 2 == 0) {
        const j = (i + k) / 2;
        if (S[i] != S[j] && S[j] != S[k] && S[k] != S[i]) {
          second += 1;
        }
      }
    })
  );
  console.log(first - second);
}

//DO NOT EDIT
Main(new NormalInput(require("fs").readFileSync("/dev/stdin", "utf8")));
//  [python]
# https://qiita.com/_-_-_-_-_/items/34f933adc7be875e61d0
# abcde	s=input()	s='abcde'
# abcde	s=list(input())	s=['a', 'b', 'c', 'd', 'e']
# 5(1つだけ)	a=int(input())	a=5
# 1 2	| x,y = map(int,input().split())   |	x=1,y=2
# 1 2 3 4 5 ... n 　	li = input().split()	li=['1','2','3',...,'n']
# 1 2 3 4 5 ... n 　	li = inpl()	li=[1,2,3,4,5,...,n]
# FFFTFTTFF 　	li = input().split('T')	li=['FFF', 'F', '', 'FF']

# INPUT
# 3
# hoge
# foo
# bar
# ANSWER
# n=int(input())
# string_list=[input() for i in range(n)]

import math
import numpy as np
import copy
from collections import defaultdict, Counter
from itertools import product
from bisect import bisect_left, bisect_right
def inpl(): return list(map(int, input().split()))

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

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

print(l[::-1][K-1])
//  [python]
def f(a):
	r = []
	for d in range(1,int(a ** 0.5) + 1):
		if a % d == 0:
			r.append(d)	
			if d * d != a: r.append(a/d)
	return r if r else [1]
a,b,k = map(int, raw_input().split(' '))
r = []
for d in f(a):
	if d in f(b):
		r.append(d)

r.sort()

print r[-k]
//  [python]
from bisect import bisect_left, bisect_right
from collections import Counter, defaultdict, deque, OrderedDict
from copy import deepcopy
from functools import lru_cache, reduce
from math import ceil, floor

import heapq
import itertools
import operator

from fractions import gcd


inf = float('inf')


def get_int():
    return int(input())


def get_str():
    return input().strip()


def get_list_of_int():
    return [int(i) for i in input().split()]


def get_char_list():
    return list(input().strip())


# inputs
A, B, K = 0, 0, 0


def set_inputs():
    global A, B, K
    A, B, K = get_list_of_int()
    x = gcd(A, B)
    y = []
    for i in range(1, x+1):
        if x % i == 0:
            y.append(i)
    print(y[-K])


def main():
    set_inputs()


if __name__ == '__main__':
    main()