'use strict'

const pair = (x) => {
  const a = x%10 // 末尾の一桁
  let b = 0

  // 一桁目の取得
  while(x) {
    b = x
    x = Math.floor(x/10)
  }

  return [a, b]
}

function Main(input) {
  input = input.trim()
  const N = parseInt(input)
  let c = 0
  let map = {}

  // 組み合わせのマップを作成する
  for(let i = 1; i <= N; ++i) {
    let p = pair(i)
    if(!map[p]) map[p] = 0
    map[p]++
  }

  // 組み合わせマップから答えを算出する
  for(let i = 1; i <= N; ++i) {
    let p = pair(i)
    let q = [p[1], p[0]]
    if(map[q]) {
      c += map[q]
    }
  }

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

Score : 400 points

Problem Statement

Given is a positive integer N.

Find the number of pairs (A, B) of positive integers not greater than N that satisfy the following condition:

When A and B are written in base ten without leading zeros, the last digit of A is equal to the first digit of B, and the first digit of A is equal to the last digit of B.

Constraints

1 \leq N \leq 2 \times 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

25

Sample Output 1

17

The following 17 pairs satisfy the condition: (1,1), (1,11), (2,2), (2,22), (3,3), (4,4), (5,5), (6,6), (7,7), (8,8), (9,9), (11,1), (11,11), (12,21), (21,12), (22,2), and (22,22).

Sample Input 2

1

Sample Output 2

1

Sample Input 3

100

Sample Output 3

108

Sample Input 4

2020

Sample Output 4

40812

Sample Input 5

200000

Sample Output 5

400000008


'use strict'

function Main(input) {

  input = input.trim()
  const N = parseInt(input)

  let c = 0
  for(let i = 1; i <= N; ++i) {
    const a = `${i}`
    for(let j = 1; j <= N; ++j) {
      const b = `${j}`

      const al = a[a.length - 1]
      const bt = b[0]

      const at = a[0]
      const bl = b[b.length - 1]

      if (al === bt && at === bl) c++

    }
  }

  console.log(c)

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

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


function Main(input) {
	input = input.trim().split("\n").map(function(x) { return x.split(" ")});
	let C = 1e9 + 7;
	let C2 = 1e5;
	let N = parseInt(input[0][0], 10);
	let v_A = input[1].map(e => parseInt(e, 10));

	let v_TF = Array.from({length: 1e3}, () => true);
	for (let i = 2;  i <= 1e3 / 2; i++){
		for (let j = 2; j <= 1e3 / i; j++){
			v_TF[i * j - 1] = false;
		}
	}
	let v_prime = [];
	for (let i = 1; i < v_TF.length; i++){
		if (v_TF[i]) v_prime.push(i + 1);
	}

	//calculate saishokobaisu
	let v_howManyTimes = Array.from({length: v_prime.length}, () => 0);
	let tmp;
	let arr_soinsu = Array.from({length: N}, () => []);
	whole_loop:
	for (let i = 0; i < N; i ++){
		tmp =  v_A[i];
		for (let j = 0; j < v_prime.length; j++){
			let count = 0;
			while (tmp % v_prime[j] === 0){
				tmp /= v_prime[j];
				count ++;
			}
			arr_soinsu[i][j] = count;
			v_howManyTimes[j] = Math.max(v_howManyTimes[j], count);
			if (tmp === 1) continue whole_loop;
		}
	}

	let P = 1;
	for (let i = 0; i < v_prime.length; i ++){
		for (let j = 1; j <= v_howManyTimes[i]; j ++){
			P = kakeruR(P, v_prime[i], C, C2);
		}
	}

	//calculate inverse
	let v_INV = INV(1e3, C, C2);

	//calculate ans

	let ans = 0;
	for (let i = 0; i < N; i ++){
		tmp = P;
		for (let j = 0; j < v_prime.length; j ++){
			if (arr_soinsu[i][j] !== 0){
				for (let k = 1; k <= arr_soinsu[i][j]; k ++){
					tmp = kakeruR(tmp, v_INV[v_prime[j]], C, C2);
				}
			}
		}
		ans += tmp;
		ans %= C;
	}
	console.log(ans);
}

function  INV(n, MOD, C2) { //return [0!^-1, 1!^-1, 2!^-1, ..., n!^-1]
    let inv;
    inv = [0,1];
    for (var i = 2; i <= n; i++){
        inv.push(MOD - kakeruR(inv[MOD%i], (MOD / i | 0), MOD, C2) % MOD);
    }
    return inv;
}

function kakeruR(a, b, C, C2){
    var tmpQ, tmpR, ans;
    tmpQ = (b / C2 | 0);
    tmpR = b - (tmpQ * C2);
    ans = (a * tmpQ % C) * C2 % C + (a * tmpR);
    ans %= C;
    return ans;
}

// function saishoKobai(x, y){
//     if (x < y) [x, y] = [y, x];
//     var tmp1 = x;
//     var tmp2 = y;
//     while (tmp2 != 0){
//         [tmp1, tmp2] = [tmp2, tmp1 % tmp2];
//     }
//     return (BigInt(x) * BigInt(y) / BigInt(tmp1));
// }

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

Score : 500 points

Problem Statement

Given are N positive integers A_1,...,A_N.

Consider positive integers B_1, ..., B_N that satisfy the following condition.

Condition: For any i, j such that 1 \leq i < j \leq N, A_i B_i = A_j B_j holds.

Find the minimum possible value of B_1 + ... + B_N for such B_1,...,B_N.

Since the answer can be enormous, print the sum modulo (10^9 +7).

Constraints

1 \leq N \leq 10^4

1 \leq A_i \leq 10^6

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 ... A_N

Output

Print the minimum possible value of B_1 + ... + B_N for B_1,...,B_N that satisfy the condition, modulo (10^9 +7).

Sample Input 1

3
2 3 4

Sample Output 1

13

Let B_1=6, B_2=4, and B_3=3, and the condition will be satisfied.

Sample Input 2

5
12 12 12 12 12

Sample Output 2

5

We can let all B_i be 1.

Sample Input 3

3
1000000 999999 999998

Sample Output 3

996989508

Print the sum modulo (10^9+7).


"use strict"

function Main(s) {
  s = s.split('\n');
  const h = Number(s[0]);
  const w = Number(s[1]);
  const n = Number(s[2]);

  if(h>w){
    console.log(Math.ceil(n/h));
  }else{
    console.log(Math.ceil(n/h));
  }
}

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

Score : 100 points

Problem Statement

We have a grid with H rows and W columns, where all the squares are initially white.

You will perform some number of painting operations on the grid.
In one operation, you can do one of the following two actions:

Choose one row, then paint all the squares in that row black.

Choose one column, then paint all the squares in that column black.

At least how many operations do you need in order to have N or more black squares in the grid?
It is guaranteed that, under the conditions in Constraints, having N or more black squares is always possible by performing some number of operations.

Constraints

1 \leq H \leq 100

1 \leq W \leq 100

1 \leq N \leq H \times W

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H
W
N

Output

Print the minimum number of operations needed.

Sample Input 1

3
7
10

Sample Output 1

2

You can have 14 black squares in the grid by performing the "row" operation twice, on different rows.

Sample Input 2

14
12
112

Sample Output 2

8

Sample Input 3

2
100
200

Sample Output 3

2


//inputに入力データ全体が入る
var alphabet="abcdefghijklmnopqrstuvwxyz"
function Main(input) {
    var tmp=inputting(input)
    console.log(alphabet.charAt(1+alphabet.indexOf(tmp[0][0])))//標準出力
}
function inputting(input){
    //標準入力で受け取ったデータを、改行区切りでi行目、空白区切りでj番目のデータが[i][j]に格納される配列に変換する
    input = input.split("\n");
    var tmp=[]
    for(var i=0;i<input.length;i++){
        tmp[i]=input[i].split(" ")
    }
    return tmp
}
function parseint_array(arr){
    var ret=[]
    for(var i=0;i<arr.length;i++){
        ret[i]=[]
        for(var j=0;j<arr[i].length;j++){
            ret[i][j]=parseInt(arr[i][j])
        }
    }
    return ret
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//Main("1\n2 3\npoyo")//標準入力サンプル

Score : 100 points

Problem Statement

Given is a lowercase English letter C that is not z. Print the letter that follows C in alphabetical order.

Constraints

C is a lowercase English letter that is not z.

Input

Input is given from Standard Input in the following format:

C

Output

Print the letter that follows C in alphabetical order.

Sample Input 1

a

Sample Output 1

b

a is followed by b.

Sample Input 2

y

Sample Output 2

z

y is followed by z.


"use strict"
function Main(input) {
  input = input.trim().split('\n');
  const N = input[0].trim().split(' ').map(Number)[0];
  const M = input[0].trim().split(' ').map(Number)[1];
  const P = input.slice(1, M+1);

  let ac = 0;
  let wa = 0;
  let tmp = 0;
  for(let i=0; i<M; i++){
    let p = P[i].trim().split(' ')[0];
    let S = P[i].trim().split(' ')[1];
    if(tmp == p) continue;

    if(S == 'WA') {
      wa += 1;
    } else {
      ac += 1;
      tmp = p;
    }
  }
  console.log(ac, wa);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 300 points

Problem Statement

Takahashi participated in a contest on AtCoder.

The contest had N problems.

Takahashi made M submissions during the contest.

The i-th submission was made for the p_i-th problem and received the verdict S_i (AC or WA).

The number of Takahashi's correct answers is the number of problems on which he received an AC once or more.

The number of Takahashi's penalties is the sum of the following count for the problems on which he received an AC once or more: the number of WAs received before receiving an AC for the first time on that problem.

Find the numbers of Takahashi's correct answers and penalties.

Constraints

N, M, and p_i are integers.

1 \leq N \leq 10^5

0 \leq M \leq 10^5

1 \leq p_i \leq N

S_i is AC or WA.

Input

Input is given from Standard Input in the following format:

N M
p_1 S_1
:
p_M S_M

Output

Print the number of Takahashi's correct answers and the number of Takahashi's penalties.

Sample Input 1

2 5
1 WA
1 AC
2 WA
2 AC
2 WA

Sample Output 1

2 2

In his second submission, he received an AC on the first problem for the first time. Before this, he received one WA on this problem.

In his fourth submission, he received an AC on the second problem for the first time. Before this, he received one WA on this problem.

Thus, he has two correct answers and two penalties.

Sample Input 2

100000 3
7777 AC
7777 AC
7777 AC

Sample Output 2

1 0

Note that it is pointless to get an AC more than once on the same problem.

Sample Input 3

6 0

Sample Output 3

0 0


function Main(input) {
    var firstLine = input[0].split(/\s/);
    var N = parseInt(firstLine[0], 10);
    var M = parseInt(firstLine[1], 10);
    var PS = input.slice(1).map(ps => {
        var psArray = ps.split(/\s/);
        psArray[0] = parseInt(psArray[0], 10);
        return psArray;
    });

    var ACList = new Array(N);
    ACList.fill(0);
    var WAList = new Array(N);
    WAList.fill(0);

    for (var i = 0; i < M; i++) {
        if (ACList[PS[i][0] - 1] === 0) {
            if (PS[i][1] === 'AC') {
                ACList[PS[i][0] - 1] = 1;
            } else {
                WAList[[PS[i][0] - 1]]++;
            }
        }
    }

    var AC = 0;
    var WA = 0;
    for (var i = 0; i < ACList.length; i++) {
        AC += ACList[i];
        WA += ACList[i] === 1 ? WAList[i] : 0;
    }

    console.log(`${AC} ${WA}`);
}

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


Main(myin());
function myin(){return require("fs").readFileSync("/dev/stdin", "utf8").trim();}
function myout(t){console.log(t);}//standard output
function myerr(t){console.error(t);}//standard error
//[no]param
//不明値:何もしない  1:数値へ変換  2:半角SPで分割  3:改行で分割  4:半角SPで分割し、数値配列へ
//5:改行で分割し、数値配列へ  6:1文字に分割  7:1文字に分割し、数値配列へ
//8:半角SPで結合　9:改行で結合　0:文字なしで結合
function myconv(i,no){switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 3:return i.split("\n");case 4:return i.split(" ").map((a)=>Number(a));case 5:return i.split("\n").map((a)=>Number(a));case 6:return i.split("");case 7:return i.split("").map((a)=>Number(a));case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}
function Main(input) {
  input = myconv(input,3);
  var H = myconv(input[0],4)[0];
  var W = myconv(input[0],4)[1];
  input.shift();
  var output = 0;
  for(var i = 0; i < H; i++){
    for(var j = 0; j < W; j++){
      var tmp = myconv(input[i],6);
      if(tmp[j] == "."){
         for(var k = 0; k < H; k++){
           for(var l = 0; l < W; l++){
             var tmp2 = myconv(input[k],6);
             if(i == k && j == l){
                continue;
             }
             if(tmp2[l] == "."){
                //ここでij地をスタート、kl地をゴールとしてtestに放り込む。
               //その時の距離をoutputに投げる
               //myout(test(i+1,j+1,k+1,l+1));
               output = Math.max(output,test(i,j,k,l));
             }
           }
         }
      }
    }
  }
  //test(1,1,3,4)
  myout(output);

  function test(sy, sx, gy, gx) {
    var count = 0;
    var r, c, sy, sx, gy, gx,q;
    r = H;
    c = W;
    var maze = input;
    var ds = [0, 1, 0, -1, 0];
    var queue = [[0, sy, sx]];
    var visited = new Array(r * c); //
    for(var i=0;i<r*c;++i){
      visited[i] = false;
    }
		//console.error(r + " " + c);
  	//console.error(sy + " " + sx);
  //console.error(gy + " " + gx);
    while (queue) {
      //myerr(queue);
        //q = queue.shift();
      	q = queue[count];
      	count++;
        if (q[1] === gy && q[2] === gx) {
            //console.log("%d", q[0]);
            return q[0];
        }
        for (var i = 0; i < 4; ++i) {
            var ny = q[1] + ds[i];
            var nx = q[2] + ds[i + 1];
            if (visited[ny * c + nx] === false && maze[ny][nx] === ".") {
                queue.push([q[0] + 1, ny, nx]);
                visited[ny * c + nx] = true;
            }
        }
    }
}

}

Score : 400 points

Problem Statement

Takahashi has a maze, which is a grid of H \times W squares with H horizontal rows and W vertical columns.

The square at the i-th row from the top and the j-th column is a "wall" square if S_{ij} is #, and a "road" square if S_{ij} is ..

From a road square, you can move to a horizontally or vertically adjacent road square.

You cannot move out of the maze, move to a wall square, or move diagonally.

Takahashi will choose a starting square and a goal square, which can be any road squares, and give the maze to Aoki.

Aoki will then travel from the starting square to the goal square, in the minimum number of moves required.

In this situation, find the maximum possible number of moves Aoki has to make.

Constraints

1 \leq H,W \leq 20

S_{ij} is . or #.

S contains at least two occurrences of ..

Any road square can be reached from any road square in zero or more moves.

Input

Input is given from Standard Input in the following format:

H W
S_{11}...S_{1W}
:
S_{H1}...S_{HW}

Output

Print the maximum possible number of moves Aoki has to make.

Sample Input 1

3 3
...
...
...

Sample Output 1

4

If Takahashi chooses the top-left square as the starting square and the bottom-right square as the goal square, Aoki has to make four moves.

Sample Input 2

3 5
...#.
.#.#.
.#...

Sample Output 2

10

If Takahashi chooses the bottom-left square as the starting square and the top-right square as the goal square, Aoki has to make ten moves.


function Main(input) {
  input=input.split("\n");
  if(input[input.length-1]===''){
    input.pop();
  }
  const N=input[0].split(' ')[0]-0;
  const S=input[1];
  var ans=0;
  for(var i=0;i<=S.length-3;i++){
    if(S.slice(i,i+3)==='ABC'){
      ans++;
    }
  }
  console.log(ans);
}

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

Score : 200 points

Problem Statement

We have a string S of length N consisting of uppercase English letters.

How many times does ABC occur in S as contiguous subsequences (see Sample Inputs and Outputs)?

Constraints

3 \leq N \leq 50

S consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print number of occurrences of ABC in S as contiguous subsequences.

Sample Input 1

10
ZABCDBABCQ

Sample Output 1

2

Two contiguous subsequences of S are equal to ABC: the 2-nd through 4-th characters, and the 7-th through 9-th characters.

Sample Input 2

19
THREEONEFOURONEFIVE

Sample Output 2

0

No contiguous subsequences of S are equal to ABC.

Sample Input 3

33
ABCCABCBABCCABACBCBBABCBCBCBCABCB

Sample Output 3

5


"use strict"
function main(arg) {
    var data = arg.trim().split("\n")
    var m = data[0].split(" ").map(Number)[1]
    var _a = data[1].split(" ").map(Number).sort((a,b) => b - a)
    var a = _a.filter(function (x, i, self) {
        return self.indexOf(x) === i;
    });
    var base = a.shift()
    var records = []
    var ans = 0
    for (var p = 1; ; p++) {
        var x = base * (p + 0.5)
        if (x > m) {
            break
        }
        var has_error = false
        for (var i = 0; i < a.length; i++) {
            var _p = x / a[i] - 0.5
            if (! Number.isInteger(_p)) {
                has_error = true
                break
            }
        }
        if (!has_error) {
            ans++
        }
    }
    console.log(ans)
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 400 points

Problem Statement

Given are a sequence A= {a_1,a_2,......a_N} of N positive even numbers, and an integer M.

Let a semi-common multiple of A be a positive integer X that satisfies the following condition for every k (1 \leq k \leq N):

There exists a non-negative integer p such that X= a_k \times (p+0.5).

Find the number of semi-common multiples of A among the integers between 1 and M (inclusive).

Constraints

1 \leq N \leq 10^5

1 \leq M \leq 10^9

2 \leq a_i \leq 10^9

a_i is an even number.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
a_1 a_2 ... a_N

Output

Print the number of semi-common multiples of A among the integers between 1 and M (inclusive).

Sample Input 1

2 50
6 10

Sample Output 1

2

15 = 6 \times 2.5

15 = 10 \times 1.5

45 = 6 \times 7.5

45 = 10 \times 4.5

Thus, 15 and 45 are semi-common multiples of A. There are no other semi-common multiples of A between 1 and 50, so the answer is 2.

Sample Input 2

3 100
14 22 40

Sample Output 2

0

The answer can be 0.

Sample Input 3

5 1000000000
6 6 2 6 2

Sample Output 3

166666667


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

var lines = [];
var reader = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
reader.on('line', (line) => {
  lines.push(line);
});
reader.on('close', () => {
  var ary = lines[0].split(" ");
  var ary[0] = ary[1];
  var ary[1] = ary[0];
  var str = ary.join("");
  console.log(str);
});

Score : 100 points

Problem Statement

Given are two strings S and T consisting of lowercase English letters. Concatenate T and S in this order, without space in between, and print the resulting string.

Constraints

S and T are strings consisting of lowercase English letters.

The lengths of S and T are between 1 and 100 (inclusive).

Input

Input is given from Standard Input in the following format:

S T

Output

Print the resulting string.

Sample Input 1

oder atc

Sample Output 1

atcoder

When S = oder and T = atc, concatenating T and S in this order results in atcoder.

Sample Input 2

humu humu

Sample Output 2

humuhumu


'use strict';
const main = input => {
  const str = input[0].split(' ');
  let s = str[0], t = str[1];
  console.log(t+s);

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


'use strict'

function main(inp) {
  inp = inp.trim().split(' ')
  console.log(inp[1]+inp[0])
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


'use strict';
function Main(inputs) {
  // 1行目がinput[0], 2行目がinput[1], …に入る
  const input = inputs.split("\n");
  const a = Number(input[0].split(' ')[0]);
  const b = Number(input[0].split(' ')[1]);
  const k = Number(input[0].split(' ')[2]);

  console.log((a > k ? a - k : 0), (a + b > k ? a + b - k : 0));
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 200 points

Problem Statement

Takahashi has A cookies, and Aoki has B cookies.
Takahashi will do the following action K times:

If Takahashi has one or more cookies, eat one of his cookies.

Otherwise, if Aoki has one or more cookies, eat one of Aoki's cookies.

If they both have no cookies, do nothing.

In the end, how many cookies will Takahashi and Aoki have, respectively?

Constraints

0 \leq A \leq 10^{12}

0 \leq B \leq 10^{12}

0 \leq K \leq 10^{12}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B K

Output

Print the numbers of Takahashi's and Aoki's cookies after K actions.

Sample Input 1

2 3 3

Sample Output 1

0 2

Takahashi will do the following:

He has two cookies, so he eats one of them.

Now he has one cookie left, and he eats it.

Now he has no cookies left, but Aoki has three, so Takahashi eats one of them.

Thus, in the end, Takahashi will have 0 cookies, and Aoki will have 2.

Sample Input 2

500000000000 500000000000 1000000000000

Sample Output 2

0 0

Watch out for overflows.


"use strict";
function Main(input) {
    const args = input.trim().split(' ').map(Number);
    const r1 = Math.max(args[0] - args[2], 0);
    const r2 = args[0] + args[1] - args[2] - r1;
    console.log('%s %s', r1, r2);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


'use strict'

function main(inp) {
  inp = inp.trim().split(' ').map(n => Number(n));
  if (inp[0] > inp[2]) {
    inp[0] = inp[0] - inp[2]
    inp[2] = 0
  } else {
    inp[2] = inp[2] - inp[0]
    inp[0] = 0
    inp[1] = inp[1] > inp[2] ? inp[1] - inp[2] : 0
  }

  console.log(inp[0] + ' ' + inp[1])
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


var input = require("fs").readFileSync("/dev/stdin", "utf8").trim().split("\n");
var obj = {
  "list" : input,
  "index" : 0,
  "max" : input.length,
  "next" : function(){
    if(!this.hasNext()){throw "NoSuchElementException:次に要素は無いよ";}
    var returnObj = this.list[this.index];
    this.index++;
    return returnObj;
  },
  "hasNext" : function(){return (this.index < this.max);}
}
Main();
function next(){return obj.next();}
function nextInt(){return myconv(next(),1);}
function nextStrArray(){return myconv(next(),2);}//半角スペース分割
function nextIntArray(){return myconv(next(),4);}//半角スペース + 数値化
function nextCharArray(){return myconv(next(),6);}//1文字分割
function hasNext(){return obj.hasNext();}
function myout(t){console.log(t);}//標準出力
function myerr(t){console.error(t);}//標準エラー出力
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す　1:数値へ変換
//2:半角SPで分割 4:半角SPで分割し、数値配列へ
//6:1文字で分割  7:1文字で分割し、数値配列へ
//8:半角SPで結合 9:改行で結合 0:文字なしで結合
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map((a)=>Number(a));case 6:return i.split("");case 7:return i.split("").map((a)=>Number(a));case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}
function Main(){
  var N = nextInt();
  while(!isPrime(N)){
    N++;
  }
  myout(N);
}
function isPrime(val){
  if(val == null || val <= 1 || (val != 2 && val % 2 == 0)){
    return false;
  }else if(val == 2){
    return true;
  }
  var root = Math.floor(Math.sqrt(val));
  for(var i = 3; i <= root; i += 2){
    if(val % i == 0){
      return false;
    }
  }
  return true;
}

Score: 300 points

Problem Statement

Find the minimum prime number greater than or equal to X.

Notes

A prime number is an integer greater than 1 that cannot be evenly divided by any positive integer except 1 and itself.

For example, 2, 3, and 5 are prime numbers, while 4 and 6 are not.

Constraints

2 \le X \le 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X

Output

Print the minimum prime number greater than or equal to X.

Sample Input 1

20

Sample Output 1

23

The minimum prime number greater than or equal to 20 is 23.

Sample Input 2

2

Sample Output 2

2

X itself can be a prime number.

Sample Input 3

99992

Sample Output 3

100003


/**
 * @param input number
 */
function Main(input) {
  // 偶数のみで検証するため2は含まない
  const prevPrimes = [];

  if (num === 2) {
    console.log(2);
    return;
  }

  var num;
  const sqrt = Math.sqrt(input);
  for (num = 3; num <= sqrt; num += 2) {
    if (isPrime(num, prevPrimes)) {
      prevPrimes.push(num);
    }
  }
  for (; true; num += 2) {
    if (isPrime(num, prevPrimes)) {
      break;
    }
  }

  console.log(prevPrimes);

  console.log(num);
}

function isPrime(num, prevPrimes) {
  return prevPrimes.every((prime) => num % prime);
}

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


/**
 * @param input string[]
 */
function Main(input) {
  /** @type number[] */
  const input0Numbered = input[0].split(' ').map(Number);
  const N = input0Numbered[0];
  const M = input0Numbered[1];
  const V = input0Numbered[2];
  const P = input0Numbered[3];
  /**
   * 昇順ソートしたもの
   * @type number[]
   */
  const alist = input[1].split(' ').map(Number).sort((v1, v2) => v1 - v2);

  /**
   * まず、昇順ソート
   * 1. 配列の最小数Kの重複分を配列から抜いて投票可能数もその分減らす
   * 2. 投票数 -= 1 ... Kに全票を入れるため
   * 3. KにM票入れた結果K2より少ない数がK以降にあれば、その差を抜いていく。その合計がMになったらv-=1これを繰り返し、余った分をRとする
   * 4. 配列の最後からv番目の数にM-Rを足した数がK2以下であれば5へ、それ以外は配列からKを抜いて1に戻る
   * 5. P位以内になれるものが見つかったら、それより少ない数を引いた問題数が結果となる
   */

  v = V;
  var ai, ai2, aj, r, j, reducedV, max = null;
  // 選ばれるための最小スコアを検索
  for (var i = 0; i < alist.length; i++) {
    // この問題と同等のスコアのものに投票していく
    while (alist[i] === alist[i + 1]) {
      i++;
      v--;
    }
    v--;
    // この問題の点数
    ai = alist[i];
    // この問題の最大点数
    ai2 = ai + M;

    r = 0;
    // aiより大きいもののうち、ai2より小さいものに順に投票していく
    for (j = i + 1; alist[j] < k2; j++) {
      r += k2 - alist[j];
    }
    reducedV = Math.floor(r / M);
    r = r % M;

    if (v <= reducedV) {
      // この時点ですべて投票済みならすべてにおいて最大となるため終了
      max = ai;
      break;
    }

    // この時点で v < alist.length - (i + 1)

    // 残りはすべてスコアが大きい順に投票
    voteds = alist.slice(-(v - reducedV)).map((aj) => aj + M);
    // 部分的に投票済みならそのうち最も少ない数から引いていく
    if (r > 0) {
      for (j = 0; j < voteds.length; j++) {
        aj = voteds[j];
        // ai2より少なくなる場合、同じ数になるまで引く
        if (aj - r < ai2) {
          voteds[j] = ai2;
          r -= aj - ai2;
        } else {
          voteds[j] -= r;
          r = 0;
          break;
        }
      }

      if (r > 0) {
        voteds[voteds.length - 1] -= r;
      }
    }

    for (k = 0; k < P; k++) {
      cmp = (k < veteds.length)
        ? veteds[veteds.length - k - 1]
        : alist[alist.length - k - 1];

      if (ai2 >= cmp) {
        max = ai;
        break;
      }
    }
    if (max) {
      break;
    }
  }

  // 最小値のインデックに戻す
  for (; i > 0; i--) {
    if (alist[i] !== alist[i - 1]) {
      break;
    }
  }

  answer = alist.length - i;

  console.log(answer);
}

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

Score : 700 points

Problem Statement

N problems are proposed for an upcoming contest. Problem i has an initial integer score of A_i points.

M judges are about to vote for problems they like. Each judge will choose exactly V problems, independently from the other judges,
and increase the score of each chosen problem by 1.

After all M judges cast their vote, the problems will be sorted in non-increasing order of score, and the first P problems will be chosen for the problemset.
Problems with the same score can be ordered arbitrarily, this order is decided by the chief judge.

How many problems out of the given N have a chance to be chosen for the problemset?

Constraints

2 \le N \le 10^5

1 \le M \le 10^9

1 \le V \le N - 1

1 \le P \le N - 1

0 \le A_i \le 10^9

Input

Input is given from Standard Input in the following format:

N M V P
A_1 A_2 ... A_N

Output

Print the number of problems that have a chance to be chosen for the problemset.

Sample Input 1

6 1 2 2
2 1 1 3 0 2

Sample Output 1

5

If the only judge votes for problems 2 and 5, the scores will be 2 2 1 3 1 2.
The problemset will consist of problem 4 and one of problems 1, 2, or 6.

If the only judge votes for problems 3 and 4, the scores will be 2 1 2 4 0 2.
The problemset will consist of problem 4 and one of problems 1, 3, or 6.

Thus, problems 1, 2, 3, 4, and 6 have a chance to be chosen for the problemset. On the contrary, there is no way for problem 5 to be chosen.

Sample Input 2

6 1 5 2
2 1 1 3 0 2

Sample Output 2

3

Only problems 1, 4, and 6 have a chance to be chosen.

Sample Input 3

10 4 8 5
7 2 3 6 1 6 5 4 6 5

Sample Output 3

8


var a = prompt("Number A?")
var b = prompt("Number B?")

console.log(6-a-b)

Score: 100 points

Problem Statement

Takahashi is solving quizzes. He has easily solved all but the last one.

The last quiz has three choices: 1, 2, and 3.

With his supernatural power, Takahashi has found out that the choices A and B are both wrong.

Print the correct choice for this problem.

Constraints

Each of the numbers A and B is 1, 2, or 3.

A and B are different.

Input

Input is given from Standard Input in the following format:

A
B

Output

Print the correct choice.

Sample Input 1

3
1

Sample Output 1

2

When we know 3 and 1 are both wrong, the correct choice is 2.

Sample Input 2

1
2

Sample Output 2

3


"use strict";
process.stdin.resume();
process.stdin.setEncoding("utf-8");

function print(x) {
  console.log(x);
}

let inputString = "";
let currentLine = 0;

process.stdin.on("data", inputStdin => {
  inputString += inputStdin;
});
process.stdin.on("end", () => {
  inputString = inputString.split("\n");
  main();
});
function readline() {
  return inputString[currentLine++];
}

// ************************ Ignore above this Line ******************************
// **************************** Main Code Start *********************************

function main() {

  var ar = readline().split(" ").map(x => parseInt(x));
  var a = ar[0],b = ar[1];
  if (a == 1 && b == 2) print('3');
  else if (a == 2 && b == 3) print('1');
  else if (a == 3 && b == 1) print('2');
}


function Main(input) {
  const N = input[0]
  const rest = input.trim().split('\n').slice(1).join()
  const array = rest.split(' ')
  const S = array[0]
  const T = array[1]
  let ans = ''
  for(let i = 0; i < N; ++i) {
    ans += S[i]
    ans += T[i]
  }

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

Score : 200 points

Problem Statement

Given are strings s and t of length N each, both consisting of lowercase English letters.

Let us form a new string by alternating the characters of S and the characters of T, as follows: the first character of S, the first character of T, the second character of S, the second character of T, ..., the N-th character of S, the N-th character of T. Print this new string.

Constraints

1 \leq N \leq 100

|S| = |T| = N

S and T are strings consisting of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
S T

Output

Print the string formed.

Sample Input 1

2
ip cc

Sample Output 1

icpc

Sample Input 2

8
hmhmnknk uuuuuuuu

Sample Output 2

humuhumunukunuku

Sample Input 3

5
aaaaa aaaaa

Sample Output 3

aaaaaaaaaa


function main(input) {
    var arr1 = input.split('\n')
    var n = arr1[0]
    var arr2 = arr1[1].split(' ')
    var s = arr2[0]
    var t = arr2[1]

    var acc = ''
    for(var i = 0; i < n; i++){
        acc += s[i]
        acc += t[i]
    }
    console.log(acc)
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function min(A,B){
i=1
  while(i>0)
    i++;
  if(i%A==0)
  {
  	if(i%B==0)
      break;
  }

  return i;
}

Score : 300 points

Problem Statement

Takahashi is organizing a party.

At the party, each guest will receive one or more snack pieces.

Takahashi predicts that the number of guests at this party will be A or B.

Find the minimum number of pieces that can be evenly distributed to the guests in both of the cases predicted.

We assume that a piece cannot be divided and distributed to multiple guests.

Constraints

1 \leq A, B \leq 10^5

A \neq B

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the minimum number of pieces that can be evenly distributed to the guests in both of the cases with A guests and B guests.

Sample Input 1

2 3

Sample Output 1

6

When we have six snack pieces, each guest can take three pieces if we have two guests, and each guest can take two if we have three guests.

Sample Input 2

123 456

Sample Output 2

18696

Sample Input 3

100000 99999

Sample Output 3

9999900000


function gcd(m, n) {
  // 剰余
  var r;

  if(m < n) {  // m >= nにする
    r = m;  //一時退避
    m = n;
    n = r;
  }

  while ((r = m % n) != 0) {
    m = n;
    n = r;
  }

  return n;
}
function Main(input){
	var a = parseInt(input[0],10);
  	var b = parseInt(input[1],10);
    console.log('%d',a * b / gcd(a, b));
}


function Main(input) {
    input = input.split("\n");

    var n = Number(input[0]);
    var rengaArr = input[1].split(" ");

    if(Math.min.apply(null,rengaArr) > 1){
        console.log("-1");
    }else{
        var res = 0;
        var ord = 1;
        for(var i=0; i<n; i++){
            if(Number(rengaArr[i])==ord){
                ord++;
            }else{
                res++;
            }
        }
        console.log(res);
    }

}

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

Score : 400 points

Problem Statement

We have N bricks arranged in a row from left to right.

The i-th brick from the left (1 \leq i \leq N) has an integer a_i written on it.

Among them, you can break at most N-1 bricks of your choice.

Let us say there are K bricks remaining. Snuke will be satisfied if, for each integer i (1 \leq i \leq K), the i-th of those brick from the left has the integer i written on it.

Find the minimum number of bricks you need to break to satisfy Snuke's desire. If his desire is unsatisfiable, print -1 instead.

Constraints

All values in input are integers.

1 \leq N \leq 200000

1 \leq a_i \leq N

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the minimum number of bricks that need to be broken to satisfy Snuke's desire, or print -1 if his desire is unsatisfiable.

Sample Input 1

3
2 1 2

Sample Output 1

1

If we break the leftmost brick, the remaining bricks have integers 1 and 2 written on them from left to right, in which case Snuke will be satisfied.

Sample Input 2

3
2 2 2

Sample Output 2

-1

In this case, there is no way to break some of the bricks to satisfy Snuke's desire.

Sample Input 3

10
3 1 4 1 5 9 2 6 5 3

Sample Output 3

7

Sample Input 4

1
1

Sample Output 4

0

There may be no need to break the bricks at all.


function Main(input) {
    input = parseInt(input);
    var result = 0;
    while(input>0){
        result += checkZero(input)
        input = input -2;
    }
    console.log(result)

}

function checkZero(multi){
    var i = true;
    multi = multi.toString()
    var index=multi.toString().length-1;
    var result = 0;
    while(i){
        if(multi[index] == "0"){
            index--;
            result++;
        }
        else{
            i = false;
        }
    }
    return result;
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 500 points

Problem Statement

For an integer n not less than 0, let us define f(n) as follows:

f(n) = 1 (if n < 2)

f(n) = n f(n-2) (if n \geq 2)

Given is an integer N. Find the number of trailing zeros in the decimal notation of f(N).

Constraints

0 \leq N \leq 10^{18}

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of trailing zeros in the decimal notation of f(N).

Sample Input 1

12

Sample Output 1

1

f(12) = 12 × 10 × 8 × 6 × 4 × 2 = 46080, which has one trailing zero.

Sample Input 2

5

Sample Output 2

0

f(5) = 5 × 3 × 1 = 15, which has no trailing zeros.

Sample Input 3

1000000000000000000

Sample Output 3

124999999999999995


"use strict";

const main = arg => {
  const a = arg.split(" ").map(x=>parseInt(x));
  if(a[0]+a[1]+a[2]>21){
  	console.log("bust");
  }
  else{
    console.log("win");
  }
  return;
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 100 points

Problem Statement

Given are three integers A_1, A_2, and A_3.

If A_1+A_2+A_3 is greater than or equal to 22, print bust; otherwise, print win.

Constraints

1 \leq A_i \leq 13 \ \ (i=1,2,3)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A_1 A_2 A_3

Output

If A_1+A_2+A_3 is greater than or equal to 22, print bust; otherwise, print win.

Sample Input 1

5 7 9

Sample Output 1

win

5+7+9=21, so print win.

Sample Input 2

13 7 2

Sample Output 2

bust

13+7+2=22, so print bust.


'use strict'
function Main(input) {

  let Aset = input.split(" ").map(v => parseInt(v));
  // console.log({ Aset });

  let Answer = Aset[0] + Aset[1] + Aset[2];
  // console.log({ Answer });
  console.log(Answer >= 22 ? 'bust' : 'win');

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


"use strict";
main(require("fs").readFileSync("/dev/stdin", "UTF-8"));

function main(input) {
  let result = 0;
  input
    .split("\n")[0]
    .split(" ")
    .map(n => (result += Number(n)));
  if (result < 22) {
    console.log("win");
  } else {
    console.log("bust");
  }
}


function Main(input) {
  var count = 0;
  var i = 0;

  var string = input.split('');

  while (i < input.length / 2) {
    var last = input.length - i - 1;

    if (string[i] !== string[last]) {
      count++;
    }
    i++;
  }

  console.log(count);
}
Main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 200 points

Problem Statement

Takahashi loves palindromes. Non-palindromic strings are unacceptable to him. Each time he hugs a string, he can change one of its characters to any character of his choice.

Given is a string S. Find the minimum number of hugs needed to make S palindromic.

Constraints

S is a string consisting of lowercase English letters.

The length of S is between 1 and 100 (inclusive).

Input

Input is given from Standard Input in the following format:

S

Output

Print the minimum number of hugs needed to make S palindromic.

Sample Input 1

redcoder

Sample Output 1

1

For example, we can change the fourth character to o and get a palindrome redooder.

Sample Input 2

vvvvvv

Sample Output 2

0

We might need no hugs at all.

Sample Input 3

abcdabc

Sample Output 3

2


function main(input){

  var leng = input.length;
  var count = 0;
  var count_max = leng/2;
  var out = 0 ;

  while(count < count_max){
    if(input[count]!=input[leng-count-1]){
      out++;
    }
    count++;
  }
  console.log(out);
}

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


'use strict';

let bigInt = function (undefined) { var BASE = 1e7, LOG_BASE = 7, MAX_INT = 9007199254740992, MAX_INT_ARR = smallToArray(MAX_INT), LOG_MAX_INT = Math.log(MAX_INT); function Integer(v, radix) { if (typeof v === "undefined") return Integer[0]; if (typeof radix !== "undefined") return +radix === 10 ? parseValue(v) : parseBase(v, radix); return parseValue(v) } function BigInteger(value, sign) { this.value = value; this.sign = sign; this.isSmall = false } BigInteger.prototype = Object.create(Integer.prototype); function SmallInteger(value) { this.value = value; this.sign = value < 0; this.isSmall = true } SmallInteger.prototype = Object.create(Integer.prototype); function isPrecise(n) { return -MAX_INT < n && n < MAX_INT } function smallToArray(n) { if (n < 1e7) return [n]; if (n < 1e14) return [n % 1e7, Math.floor(n / 1e7)]; return [n % 1e7, Math.floor(n / 1e7) % 1e7, Math.floor(n / 1e14)] } function arrayToSmall(arr) { trim(arr); var length = arr.length; if (length < 4 && compareAbs(arr, MAX_INT_ARR) < 0) { switch (length) { case 0: return 0; case 1: return arr[0]; case 2: return arr[0] + arr[1] * BASE; default: return arr[0] + (arr[1] + arr[2] * BASE) * BASE } } return arr } function trim(v) { var i = v.length; while (v[--i] === 0); v.length = i + 1 } function createArray(length) { var x = new Array(length); var i = -1; while (++i < length) { x[i] = 0 } return x } function truncate(n) { if (n > 0) return Math.floor(n); return Math.ceil(n) } function add(a, b) { var l_a = a.length, l_b = b.length, r = new Array(l_a), carry = 0, base = BASE, sum, i; for (i = 0; i < l_b; i++) { sum = a[i] + b[i] + carry; carry = sum >= base ? 1 : 0; r[i] = sum - carry * base } while (i < l_a) { sum = a[i] + carry; carry = sum === base ? 1 : 0; r[i++] = sum - carry * base } if (carry > 0) r.push(carry); return r } function addAny(a, b) { if (a.length >= b.length) return add(a, b); return add(b, a) } function addSmall(a, carry) { var l = a.length, r = new Array(l), base = BASE, sum, i; for (i = 0; i < l; i++) { sum = a[i] - base + carry; carry = Math.floor(sum / base); r[i] = sum - carry * base; carry += 1 } while (carry > 0) { r[i++] = carry % base; carry = Math.floor(carry / base) } return r } BigInteger.prototype.add = function (v) { var n = parseValue(v); if (this.sign !== n.sign) { return this.subtract(n.negate()) } var a = this.value, b = n.value; if (n.isSmall) { return new BigInteger(addSmall(a, Math.abs(b)), this.sign) } return new BigInteger(addAny(a, b), this.sign) }; BigInteger.prototype.plus = BigInteger.prototype.add; SmallInteger.prototype.add = function (v) { var n = parseValue(v); var a = this.value; if (a < 0 !== n.sign) { return this.subtract(n.negate()) } var b = n.value; if (n.isSmall) { if (isPrecise(a + b)) return new SmallInteger(a + b); b = smallToArray(Math.abs(b)) } return new BigInteger(addSmall(b, Math.abs(a)), a < 0) }; SmallInteger.prototype.plus = SmallInteger.prototype.add; function subtract(a, b) { var a_l = a.length, b_l = b.length, r = new Array(a_l), borrow = 0, base = BASE, i, difference; for (i = 0; i < b_l; i++) { difference = a[i] - borrow - b[i]; if (difference < 0) { difference += base; borrow = 1 } else borrow = 0; r[i] = difference } for (i = b_l; i < a_l; i++) { difference = a[i] - borrow; if (difference < 0) difference += base; else { r[i++] = difference; break } r[i] = difference } for (; i < a_l; i++) { r[i] = a[i] } trim(r); return r } function subtractAny(a, b, sign) { var value; if (compareAbs(a, b) >= 0) { value = subtract(a, b) } else { value = subtract(b, a); sign = !sign } value = arrayToSmall(value); if (typeof value === "number") { if (sign) value = -value; return new SmallInteger(value) } return new BigInteger(value, sign) } function subtractSmall(a, b, sign) { var l = a.length, r = new Array(l), carry = -b, base = BASE, i, difference; for (i = 0; i < l; i++) { difference = a[i] + carry; carry = Math.floor(difference / base); difference %= base; r[i] = difference < 0 ? difference + base : difference } r = arrayToSmall(r); if (typeof r === "number") { if (sign) r = -r; return new SmallInteger(r) } return new BigInteger(r, sign) } BigInteger.prototype.subtract = function (v) { var n = parseValue(v); if (this.sign !== n.sign) { return this.add(n.negate()) } var a = this.value, b = n.value; if (n.isSmall) return subtractSmall(a, Math.abs(b), this.sign); return subtractAny(a, b, this.sign) }; BigInteger.prototype.minus = BigInteger.prototype.subtract; SmallInteger.prototype.subtract = function (v) { var n = parseValue(v); var a = this.value; if (a < 0 !== n.sign) { return this.add(n.negate()) } var b = n.value; if (n.isSmall) { return new SmallInteger(a - b) } return subtractSmall(b, Math.abs(a), a >= 0) }; SmallInteger.prototype.minus = SmallInteger.prototype.subtract; BigInteger.prototype.negate = function () { return new BigInteger(this.value, !this.sign) }; SmallInteger.prototype.negate = function () { var sign = this.sign; var small = new SmallInteger(-this.value); small.sign = !sign; return small }; BigInteger.prototype.abs = function () { return new BigInteger(this.value, false) }; SmallInteger.prototype.abs = function () { return new SmallInteger(Math.abs(this.value)) }; function multiplyLong(a, b) { var a_l = a.length, b_l = b.length, l = a_l + b_l, r = createArray(l), base = BASE, product, carry, i, a_i, b_j; for (i = 0; i < a_l; ++i) { a_i = a[i]; for (var j = 0; j < b_l; ++j) { b_j = b[j]; product = a_i * b_j + r[i + j]; carry = Math.floor(product / base); r[i + j] = product - carry * base; r[i + j + 1] += carry } } trim(r); return r } function multiplySmall(a, b) { var l = a.length, r = new Array(l), base = BASE, carry = 0, product, i; for (i = 0; i < l; i++) { product = a[i] * b + carry; carry = Math.floor(product / base); r[i] = product - carry * base } while (carry > 0) { r[i++] = carry % base; carry = Math.floor(carry / base) } return r } function shiftLeft(x, n) { var r = []; while (n-- > 0) r.push(0); return r.concat(x) } function multiplyKaratsuba(x, y) { var n = Math.max(x.length, y.length); if (n <= 30) return multiplyLong(x, y); n = Math.ceil(n / 2); var b = x.slice(n), a = x.slice(0, n), d = y.slice(n), c = y.slice(0, n); var ac = multiplyKaratsuba(a, c), bd = multiplyKaratsuba(b, d), abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d)); var product = addAny(addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)), shiftLeft(bd, 2 * n)); trim(product); return product } function useKaratsuba(l1, l2) { return -.012 * l1 - .012 * l2 + 15e-6 * l1 * l2 > 0 } BigInteger.prototype.multiply = function (v) { var n = parseValue(v), a = this.value, b = n.value, sign = this.sign !== n.sign, abs; if (n.isSmall) { if (b === 0) return Integer[0]; if (b === 1) return this; if (b === -1) return this.negate(); abs = Math.abs(b); if (abs < BASE) { return new BigInteger(multiplySmall(a, abs), sign) } b = smallToArray(abs) } if (useKaratsuba(a.length, b.length)) return new BigInteger(multiplyKaratsuba(a, b), sign); return new BigInteger(multiplyLong(a, b), sign) }; BigInteger.prototype.times = BigInteger.prototype.multiply; function multiplySmallAndArray(a, b, sign) { if (a < BASE) { return new BigInteger(multiplySmall(b, a), sign) } return new BigInteger(multiplyLong(b, smallToArray(a)), sign) } SmallInteger.prototype._multiplyBySmall = function (a) { if (isPrecise(a.value * this.value)) { return new SmallInteger(a.value * this.value) } return multiplySmallAndArray(Math.abs(a.value), smallToArray(Math.abs(this.value)), this.sign !== a.sign) }; BigInteger.prototype._multiplyBySmall = function (a) { if (a.value === 0) return Integer[0]; if (a.value === 1) return this; if (a.value === -1) return this.negate(); return multiplySmallAndArray(Math.abs(a.value), this.value, this.sign !== a.sign) }; SmallInteger.prototype.multiply = function (v) { return parseValue(v)._multiplyBySmall(this) }; SmallInteger.prototype.times = SmallInteger.prototype.multiply; function square(a) { var l = a.length, r = createArray(l + l), base = BASE, product, carry, i, a_i, a_j; for (i = 0; i < l; i++) { a_i = a[i]; carry = 0 - a_i * a_i; for (var j = i; j < l; j++) { a_j = a[j]; product = 2 * (a_i * a_j) + r[i + j] + carry; carry = Math.floor(product / base); r[i + j] = product - carry * base } r[i + l] = carry } trim(r); return r } BigInteger.prototype.square = function () { return new BigInteger(square(this.value), false) }; SmallInteger.prototype.square = function () { var value = this.value * this.value; if (isPrecise(value)) return new SmallInteger(value); return new BigInteger(square(smallToArray(Math.abs(this.value))), false) }; function divMod1(a, b) { var a_l = a.length, b_l = b.length, base = BASE, result = createArray(b.length), divisorMostSignificantDigit = b[b_l - 1], lambda = Math.ceil(base / (2 * divisorMostSignificantDigit)), remainder = multiplySmall(a, lambda), divisor = multiplySmall(b, lambda), quotientDigit, shift, carry, borrow, i, l, q; if (remainder.length <= a_l) remainder.push(0); divisor.push(0); divisorMostSignificantDigit = divisor[b_l - 1]; for (shift = a_l - b_l; shift >= 0; shift--) { quotientDigit = base - 1; if (remainder[shift + b_l] !== divisorMostSignificantDigit) { quotientDigit = Math.floor((remainder[shift + b_l] * base + remainder[shift + b_l - 1]) / divisorMostSignificantDigit) } carry = 0; borrow = 0; l = divisor.length; for (i = 0; i < l; i++) { carry += quotientDigit * divisor[i]; q = Math.floor(carry / base); borrow += remainder[shift + i] - (carry - q * base); carry = q; if (borrow < 0) { remainder[shift + i] = borrow + base; borrow = -1 } else { remainder[shift + i] = borrow; borrow = 0 } } while (borrow !== 0) { quotientDigit -= 1; carry = 0; for (i = 0; i < l; i++) { carry += remainder[shift + i] - base + divisor[i]; if (carry < 0) { remainder[shift + i] = carry + base; carry = 0 } else { remainder[shift + i] = carry; carry = 1 } } borrow += carry } result[shift] = quotientDigit } remainder = divModSmall(remainder, lambda)[0]; return [arrayToSmall(result), arrayToSmall(remainder)] } function divMod2(a, b) { var a_l = a.length, b_l = b.length, result = [], part = [], base = BASE, guess, xlen, highx, highy, check; while (a_l) { part.unshift(a[--a_l]); trim(part); if (compareAbs(part, b) < 0) { result.push(0); continue } xlen = part.length; highx = part[xlen - 1] * base + part[xlen - 2]; highy = b[b_l - 1] * base + b[b_l - 2]; if (xlen > b_l) { highx = (highx + 1) * base } guess = Math.ceil(highx / highy); do { check = multiplySmall(b, guess); if (compareAbs(check, part) <= 0) break; guess-- } while (guess); result.push(guess); part = subtract(part, check) } result.reverse(); return [arrayToSmall(result), arrayToSmall(part)] } function divModSmall(value, lambda) { var length = value.length, quotient = createArray(length), base = BASE, i, q, remainder, divisor; remainder = 0; for (i = length - 1; i >= 0; --i) { divisor = remainder * base + value[i]; q = truncate(divisor / lambda); remainder = divisor - q * lambda; quotient[i] = q | 0 } return [quotient, remainder | 0] } function divModAny(self, v) { var value, n = parseValue(v); var a = self.value, b = n.value; var quotient; if (b === 0) throw new Error("Cannot divide by zero"); if (self.isSmall) { if (n.isSmall) { return [new SmallInteger(truncate(a / b)), new SmallInteger(a % b)] } return [Integer[0], self] } if (n.isSmall) { if (b === 1) return [self, Integer[0]]; if (b == -1) return [self.negate(), Integer[0]]; var abs = Math.abs(b); if (abs < BASE) { value = divModSmall(a, abs); quotient = arrayToSmall(value[0]); var remainder = value[1]; if (self.sign) remainder = -remainder; if (typeof quotient === "number") { if (self.sign !== n.sign) quotient = -quotient; return [new SmallInteger(quotient), new SmallInteger(remainder)] } return [new BigInteger(quotient, self.sign !== n.sign), new SmallInteger(remainder)] } b = smallToArray(abs) } var comparison = compareAbs(a, b); if (comparison === -1) return [Integer[0], self]; if (comparison === 0) return [Integer[self.sign === n.sign ? 1 : -1], Integer[0]]; if (a.length + b.length <= 200) value = divMod1(a, b); else value = divMod2(a, b); quotient = value[0]; var qSign = self.sign !== n.sign, mod = value[1], mSign = self.sign; if (typeof quotient === "number") { if (qSign) quotient = -quotient; quotient = new SmallInteger(quotient) } else quotient = new BigInteger(quotient, qSign); if (typeof mod === "number") { if (mSign) mod = -mod; mod = new SmallInteger(mod) } else mod = new BigInteger(mod, mSign); return [quotient, mod] } BigInteger.prototype.divmod = function (v) { var result = divModAny(this, v); return { quotient: result[0], remainder: result[1] } }; SmallInteger.prototype.divmod = BigInteger.prototype.divmod; BigInteger.prototype.divide = function (v) { return divModAny(this, v)[0] }; SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over = BigInteger.prototype.divide; BigInteger.prototype.mod = function (v) { return divModAny(this, v)[1] }; SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder = BigInteger.prototype.mod; BigInteger.prototype.pow = function (v) { var n = parseValue(v), a = this.value, b = n.value, value, x, y; if (b === 0) return Integer[1]; if (a === 0) return Integer[0]; if (a === 1) return Integer[1]; if (a === -1) return n.isEven() ? Integer[1] : Integer[-1]; if (n.sign) { return Integer[0] } if (!n.isSmall) throw new Error("The exponent " + n.toString() + " is too large."); if (this.isSmall) { if (isPrecise(value = Math.pow(a, b))) return new SmallInteger(truncate(value)) } x = this; y = Integer[1]; while (true) { if (b & 1 === 1) { y = y.times(x); --b } if (b === 0) break; b /= 2; x = x.square() } return y }; SmallInteger.prototype.pow = BigInteger.prototype.pow; BigInteger.prototype.modPow = function (exp, mod) { exp = parseValue(exp); mod = parseValue(mod); if (mod.isZero()) throw new Error("Cannot take modPow with modulus 0"); var r = Integer[1], base = this.mod(mod); while (exp.isPositive()) { if (base.isZero()) return Integer[0]; if (exp.isOdd()) r = r.multiply(base).mod(mod); exp = exp.divide(2); base = base.square().mod(mod) } return r }; SmallInteger.prototype.modPow = BigInteger.prototype.modPow; function compareAbs(a, b) { if (a.length !== b.length) { return a.length > b.length ? 1 : -1 } for (var i = a.length - 1; i >= 0; i--) { if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1 } return 0 } BigInteger.prototype.compareAbs = function (v) { var n = parseValue(v), a = this.value, b = n.value; if (n.isSmall) return 1; return compareAbs(a, b) }; SmallInteger.prototype.compareAbs = function (v) { var n = parseValue(v), a = Math.abs(this.value), b = n.value; if (n.isSmall) { b = Math.abs(b); return a === b ? 0 : a > b ? 1 : -1 } return -1 }; BigInteger.prototype.compare = function (v) { if (v === Infinity) { return -1 } if (v === -Infinity) { return 1 } var n = parseValue(v), a = this.value, b = n.value; if (this.sign !== n.sign) { return n.sign ? 1 : -1 } if (n.isSmall) { return this.sign ? -1 : 1 } return compareAbs(a, b) * (this.sign ? -1 : 1) }; BigInteger.prototype.compareTo = BigInteger.prototype.compare; SmallInteger.prototype.compare = function (v) { if (v === Infinity) { return -1 } if (v === -Infinity) { return 1 } var n = parseValue(v), a = this.value, b = n.value; if (n.isSmall) { return a == b ? 0 : a > b ? 1 : -1 } if (a < 0 !== n.sign) { return a < 0 ? -1 : 1 } return a < 0 ? 1 : -1 }; SmallInteger.prototype.compareTo = SmallInteger.prototype.compare; BigInteger.prototype.equals = function (v) { return this.compare(v) === 0 }; SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq = BigInteger.prototype.equals; BigInteger.prototype.notEquals = function (v) { return this.compare(v) !== 0 }; SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq = BigInteger.prototype.notEquals; BigInteger.prototype.greater = function (v) { return this.compare(v) > 0 }; SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt = BigInteger.prototype.greater; BigInteger.prototype.lesser = function (v) { return this.compare(v) < 0 }; SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt = BigInteger.prototype.lesser; BigInteger.prototype.greaterOrEquals = function (v) { return this.compare(v) >= 0 }; SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq = BigInteger.prototype.greaterOrEquals; BigInteger.prototype.lesserOrEquals = function (v) { return this.compare(v) <= 0 }; SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq = BigInteger.prototype.lesserOrEquals; BigInteger.prototype.isEven = function () { return (this.value[0] & 1) === 0 }; SmallInteger.prototype.isEven = function () { return (this.value & 1) === 0 }; BigInteger.prototype.isOdd = function () { return (this.value[0] & 1) === 1 }; SmallInteger.prototype.isOdd = function () { return (this.value & 1) === 1 }; BigInteger.prototype.isPositive = function () { return !this.sign }; SmallInteger.prototype.isPositive = function () { return this.value > 0 }; BigInteger.prototype.isNegative = function () { return this.sign }; SmallInteger.prototype.isNegative = function () { return this.value < 0 }; BigInteger.prototype.isUnit = function () { return false }; SmallInteger.prototype.isUnit = function () { return Math.abs(this.value) === 1 }; BigInteger.prototype.isZero = function () { return false }; SmallInteger.prototype.isZero = function () { return this.value === 0 }; BigInteger.prototype.isDivisibleBy = function (v) { var n = parseValue(v); var value = n.value; if (value === 0) return false; if (value === 1) return true; if (value === 2) return this.isEven(); return this.mod(n).equals(Integer[0]) }; SmallInteger.prototype.isDivisibleBy = BigInteger.prototype.isDivisibleBy; function isBasicPrime(v) { var n = v.abs(); if (n.isUnit()) return false; if (n.equals(2) || n.equals(3) || n.equals(5)) return true; if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5)) return false; if (n.lesser(25)) return true } BigInteger.prototype.isPrime = function () { var isPrime = isBasicPrime(this); if (isPrime !== undefined) return isPrime; var n = this.abs(), nPrev = n.prev(); var a = [2, 3, 5, 7, 11, 13, 17, 19], b = nPrev, d, t, i, x; while (b.isEven()) b = b.divide(2); for (i = 0; i < a.length; i++) { x = bigInt(a[i]).modPow(b, n); if (x.equals(Integer[1]) || x.equals(nPrev)) continue; for (t = true, d = b; t && d.lesser(nPrev); d = d.multiply(2)) { x = x.square().mod(n); if (x.equals(nPrev)) t = false } if (t) return false } return true }; SmallInteger.prototype.isPrime = BigInteger.prototype.isPrime; BigInteger.prototype.isProbablePrime = function (iterations) { var isPrime = isBasicPrime(this); if (isPrime !== undefined) return isPrime; var n = this.abs(); var t = iterations === undefined ? 5 : iterations; for (var i = 0; i < t; i++) { var a = bigInt.randBetween(2, n.minus(2)); if (!a.modPow(n.prev(), n).isUnit()) return false } return true }; SmallInteger.prototype.isProbablePrime = BigInteger.prototype.isProbablePrime; BigInteger.prototype.modInv = function (n) { var t = bigInt.zero, newT = bigInt.one, r = parseValue(n), newR = this.abs(), q, lastT, lastR; while (!newR.equals(bigInt.zero)) { q = r.divide(newR); lastT = t; lastR = r; t = newT; r = newR; newT = lastT.subtract(q.multiply(newT)); newR = lastR.subtract(q.multiply(newR)) } if (!r.equals(1)) throw new Error(this.toString() + " and " + n.toString() + " are not co-prime"); if (t.compare(0) === -1) { t = t.add(n) } if (this.isNegative()) { return t.negate() } return t }; SmallInteger.prototype.modInv = BigInteger.prototype.modInv; BigInteger.prototype.next = function () { var value = this.value; if (this.sign) { return subtractSmall(value, 1, this.sign) } return new BigInteger(addSmall(value, 1), this.sign) }; SmallInteger.prototype.next = function () { var value = this.value; if (value + 1 < MAX_INT) return new SmallInteger(value + 1); return new BigInteger(MAX_INT_ARR, false) }; BigInteger.prototype.prev = function () { var value = this.value; if (this.sign) { return new BigInteger(addSmall(value, 1), true) } return subtractSmall(value, 1, this.sign) }; SmallInteger.prototype.prev = function () { var value = this.value; if (value - 1 > -MAX_INT) return new SmallInteger(value - 1); return new BigInteger(MAX_INT_ARR, true) }; var powersOfTwo = [1]; while (2 * powersOfTwo[powersOfTwo.length - 1] <= BASE) powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]); var powers2Length = powersOfTwo.length, highestPower2 = powersOfTwo[powers2Length - 1]; function shift_isSmall(n) { return (typeof n === "number" || typeof n === "string") && +Math.abs(n) <= BASE || n instanceof BigInteger && n.value.length <= 1 } BigInteger.prototype.shiftLeft = function (n) { if (!shift_isSmall(n)) { throw new Error(String(n) + " is too large for shifting.") } n = +n; if (n < 0) return this.shiftRight(-n); var result = this; if (result.isZero()) return result; while (n >= powers2Length) { result = result.multiply(highestPower2); n -= powers2Length - 1 } return result.multiply(powersOfTwo[n]) }; SmallInteger.prototype.shiftLeft = BigInteger.prototype.shiftLeft; BigInteger.prototype.shiftRight = function (n) { var remQuo; if (!shift_isSmall(n)) { throw new Error(String(n) + " is too large for shifting.") } n = +n; if (n < 0) return this.shiftLeft(-n); var result = this; while (n >= powers2Length) { if (result.isZero() || result.isNegative() && result.isUnit()) return result; remQuo = divModAny(result, highestPower2); result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0]; n -= powers2Length - 1 } remQuo = divModAny(result, powersOfTwo[n]); return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0] }; SmallInteger.prototype.shiftRight = BigInteger.prototype.shiftRight; function bitwise(x, y, fn) { y = parseValue(y); var xSign = x.isNegative(), ySign = y.isNegative(); var xRem = xSign ? x.not() : x, yRem = ySign ? y.not() : y; var xDigit = 0, yDigit = 0; var xDivMod = null, yDivMod = null; var result = []; while (!xRem.isZero() || !yRem.isZero()) { xDivMod = divModAny(xRem, highestPower2); xDigit = xDivMod[1].toJSNumber(); if (xSign) { xDigit = highestPower2 - 1 - xDigit } yDivMod = divModAny(yRem, highestPower2); yDigit = yDivMod[1].toJSNumber(); if (ySign) { yDigit = highestPower2 - 1 - yDigit } xRem = xDivMod[0]; yRem = yDivMod[0]; result.push(fn(xDigit, yDigit)) } var sum = fn(xSign ? 1 : 0, ySign ? 1 : 0) !== 0 ? bigInt(-1) : bigInt(0); for (var i = result.length - 1; i >= 0; i -= 1) { sum = sum.multiply(highestPower2).add(bigInt(result[i])) } return sum } BigInteger.prototype.not = function () { return this.negate().prev() }; SmallInteger.prototype.not = BigInteger.prototype.not; BigInteger.prototype.and = function (n) { return bitwise(this, n, function (a, b) { return a & b }) }; SmallInteger.prototype.and = BigInteger.prototype.and; BigInteger.prototype.or = function (n) { return bitwise(this, n, function (a, b) { return a | b }) }; SmallInteger.prototype.or = BigInteger.prototype.or; BigInteger.prototype.xor = function (n) { return bitwise(this, n, function (a, b) { return a ^ b }) }; SmallInteger.prototype.xor = BigInteger.prototype.xor; var LOBMASK_I = 1 << 30, LOBMASK_BI = (BASE & -BASE) * (BASE & -BASE) | LOBMASK_I; function roughLOB(n) { var v = n.value, x = typeof v === "number" ? v | LOBMASK_I : v[0] + v[1] * BASE | LOBMASK_BI; return x & -x } function integerLogarithm(value, base) { if (base.compareTo(value) <= 0) { var tmp = integerLogarithm(value, base.square(base)); var p = tmp.p; var e = tmp.e; var t = p.multiply(base); return t.compareTo(value) <= 0 ? { p: t, e: e * 2 + 1 } : { p: p, e: e * 2 } } return { p: bigInt(1), e: 0 } } BigInteger.prototype.bitLength = function () { var n = this; if (n.compareTo(bigInt(0)) < 0) { n = n.negate().subtract(bigInt(1)) } if (n.compareTo(bigInt(0)) === 0) { return bigInt(0) } return bigInt(integerLogarithm(n, bigInt(2)).e).add(bigInt(1)) }; SmallInteger.prototype.bitLength = BigInteger.prototype.bitLength; function max(a, b) { a = parseValue(a); b = parseValue(b); return a.greater(b) ? a : b } function min(a, b) { a = parseValue(a); b = parseValue(b); return a.lesser(b) ? a : b } function gcd(a, b) { a = parseValue(a).abs(); b = parseValue(b).abs(); if (a.equals(b)) return a; if (a.isZero()) return b; if (b.isZero()) return a; var c = Integer[1], d, t; while (a.isEven() && b.isEven()) { d = Math.min(roughLOB(a), roughLOB(b)); a = a.divide(d); b = b.divide(d); c = c.multiply(d) } while (a.isEven()) { a = a.divide(roughLOB(a)) } do { while (b.isEven()) { b = b.divide(roughLOB(b)) } if (a.greater(b)) { t = b; b = a; a = t } b = b.subtract(a) } while (!b.isZero()); return c.isUnit() ? a : a.multiply(c) } function lcm(a, b) { a = parseValue(a).abs(); b = parseValue(b).abs(); return a.divide(gcd(a, b)).multiply(b) } function randBetween(a, b) { a = parseValue(a); b = parseValue(b); var low = min(a, b), high = max(a, b); var range = high.subtract(low).add(1); if (range.isSmall) return low.add(Math.floor(Math.random() * range)); var length = range.value.length - 1; var result = [], restricted = true; for (var i = length; i >= 0; i--) { var top = restricted ? range.value[i] : BASE; var digit = truncate(Math.random() * top); result.unshift(digit); if (digit < top) restricted = false } result = arrayToSmall(result); return low.add(typeof result === "number" ? new SmallInteger(result) : new BigInteger(result, false)) } var parseBase = function (text, base) { var length = text.length; var i; var absBase = Math.abs(base); for (var i = 0; i < length; i++) { var c = text[i].toLowerCase(); if (c === "-") continue; if (/[a-z0-9]/.test(c)) { if (/[0-9]/.test(c) && +c >= absBase) { if (c === "1" && absBase === 1) continue; throw new Error(c + " is not a valid digit in base " + base + ".") } else if (c.charCodeAt(0) - 87 >= absBase) { throw new Error(c + " is not a valid digit in base " + base + ".") } } } if (2 <= base && base <= 36) { if (length <= LOG_MAX_INT / Math.log(base)) { var result = parseInt(text, base); if (isNaN(result)) { throw new Error(c + " is not a valid digit in base " + base + ".") } return new SmallInteger(parseInt(text, base)) } } base = parseValue(base); var digits = []; var isNegative = text[0] === "-"; for (i = isNegative ? 1 : 0; i < text.length; i++) { var c = text[i].toLowerCase(), charCode = c.charCodeAt(0); if (48 <= charCode && charCode <= 57) digits.push(parseValue(c)); else if (97 <= charCode && charCode <= 122) digits.push(parseValue(c.charCodeAt(0) - 87)); else if (c === "<") { var start = i; do { i++ } while (text[i] !== ">"); digits.push(parseValue(text.slice(start + 1, i))) } else throw new Error(c + " is not a valid character") } return parseBaseFromArray(digits, base, isNegative) }; function parseBaseFromArray(digits, base, isNegative) { var val = Integer[0], pow = Integer[1], i; for (i = digits.length - 1; i >= 0; i--) { val = val.add(digits[i].times(pow)); pow = pow.times(base) } return isNegative ? val.negate() : val } function stringify(digit) { if (digit <= 35) { return "0123456789abcdefghijklmnopqrstuvwxyz".charAt(digit) } return "<" + digit + ">" } function toBase(n, base) { base = bigInt(base); if (base.isZero()) { if (n.isZero()) return { value: [0], isNegative: false }; throw new Error("Cannot convert nonzero numbers to base 0.") } if (base.equals(-1)) { if (n.isZero()) return { value: [0], isNegative: false }; if (n.isNegative()) return { value: [].concat.apply([], Array.apply(null, Array(-n)).map(Array.prototype.valueOf, [1, 0])), isNegative: false }; var arr = Array.apply(null, Array(+n - 1)).map(Array.prototype.valueOf, [0, 1]); arr.unshift([1]); return { value: [].concat.apply([], arr), isNegative: false } } var neg = false; if (n.isNegative() && base.isPositive()) { neg = true; n = n.abs() } if (base.equals(1)) { if (n.isZero()) return { value: [0], isNegative: false }; return { value: Array.apply(null, Array(+n)).map(Number.prototype.valueOf, 1), isNegative: neg } } var out = []; var left = n, divmod; while (left.isNegative() || left.compareAbs(base) >= 0) { divmod = left.divmod(base); left = divmod.quotient; var digit = divmod.remainder; if (digit.isNegative()) { digit = base.minus(digit).abs(); left = left.next() } out.push(digit.toJSNumber()) } out.push(left.toJSNumber()); return { value: out.reverse(), isNegative: neg } } function toBaseString(n, base) { var arr = toBase(n, base); return (arr.isNegative ? "-" : "") + arr.value.map(stringify).join("") } BigInteger.prototype.toArray = function (radix) { return toBase(this, radix) }; SmallInteger.prototype.toArray = function (radix) { return toBase(this, radix) }; BigInteger.prototype.toString = function (radix) { if (radix === undefined) radix = 10; if (radix !== 10) return toBaseString(this, radix); var v = this.value, l = v.length, str = String(v[--l]), zeros = "0000000", digit; while (--l >= 0) { digit = String(v[l]); str += zeros.slice(digit.length) + digit } var sign = this.sign ? "-" : ""; return sign + str }; SmallInteger.prototype.toString = function (radix) { if (radix === undefined) radix = 10; if (radix != 10) return toBaseString(this, radix); return String(this.value) }; BigInteger.prototype.toJSON = SmallInteger.prototype.toJSON = function () { return this.toString() }; BigInteger.prototype.valueOf = function () { return parseInt(this.toString(), 10) }; BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf; SmallInteger.prototype.valueOf = function () { return this.value }; SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf; function parseStringValue(v) { if (isPrecise(+v)) { var x = +v; if (x === truncate(x)) return new SmallInteger(x); throw new Error("Invalid integer: " + v) } var sign = v[0] === "-"; if (sign) v = v.slice(1); var split = v.split(/e/i); if (split.length > 2) throw new Error("Invalid integer: " + split.join("e")); if (split.length === 2) { var exp = split[1]; if (exp[0] === "+") exp = exp.slice(1); exp = +exp; if (exp !== truncate(exp) || !isPrecise(exp)) throw new Error("Invalid integer: " + exp + " is not a valid exponent."); var text = split[0]; var decimalPlace = text.indexOf("."); if (decimalPlace >= 0) { exp -= text.length - decimalPlace - 1; text = text.slice(0, decimalPlace) + text.slice(decimalPlace + 1) } if (exp < 0) throw new Error("Cannot include negative exponent part for integers"); text += new Array(exp + 1).join("0"); v = text } var isValid = /^([0-9][0-9]*)$/.test(v); if (!isValid) throw new Error("Invalid integer: " + v); var r = [], max = v.length, l = LOG_BASE, min = max - l; while (max > 0) { r.push(+v.slice(min, max)); min -= l; if (min < 0) min = 0; max -= l } trim(r); return new BigInteger(r, sign) } function parseNumberValue(v) { if (isPrecise(v)) { if (v !== truncate(v)) throw new Error(v + " is not an integer."); return new SmallInteger(v) } return parseStringValue(v.toString()) } function parseValue(v) { if (typeof v === "number") { return parseNumberValue(v) } if (typeof v === "string") { return parseStringValue(v) } return v } for (var i = 0; i < 1e3; i++) { Integer[i] = new SmallInteger(i); if (i > 0) Integer[-i] = new SmallInteger(-i) } Integer.one = Integer[1]; Integer.zero = Integer[0]; Integer.minusOne = Integer[-1]; Integer.max = max; Integer.min = min; Integer.gcd = gcd; Integer.lcm = lcm; Integer.isInstance = function (x) { return x instanceof BigInteger || x instanceof SmallInteger }; Integer.randBetween = randBetween; Integer.fromArray = function (digits, base, isNegative) { return parseBaseFromArray(digits.map(parseValue), parseValue(base || 10), isNegative) }; return Integer }();

const input = require("fs").readFileSync("/dev/stdin", "utf8");
const rows = input.trim().split('\n');

const N = Number(rows[0].trim());
const An = rows[1].trim().split(' ').map((v) => {
    return bigInt(v);
});

let sum = bigInt(0);
for (let i = 0; i < N - 1; i++) {
    for (let j = i + 1; j < N; j++) {
        sum = sum.add(An[i].xor(An[j]));
    }
}

console.log(sum.mod(1000000007).toString());

Score : 400 points

Problem Statement

We have N integers. The i-th integer is A_i.

Find \sum_{i=1}^{N-1}\sum_{j=i+1}^{N} (A_i \mbox{ XOR } A_j), modulo (10^9+7).

What is \mbox{ XOR }?

The XOR of integers A and B, A \mbox{ XOR } B, is defined as follows:

When A \mbox{ XOR } B is written in base two, the digit in the 2^k's place (k \geq 0) is 1 if either A or B, but not both, has 1 in the 2^k's place, and 0 otherwise.

For example, 3 \mbox{ XOR } 5 = 6. (In base two: 011 \mbox{ XOR } 101 = 110.)

Constraints

2 \leq N \leq 3 \times 10^5

0 \leq A_i < 2^{60}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the value \sum_{i=1}^{N-1}\sum_{j=i+1}^{N} (A_i \mbox{ XOR } A_j), modulo (10^9+7).

Sample Input 1

3
1 2 3

Sample Output 1

6

We have (1\mbox{ XOR } 2)+(1\mbox{ XOR } 3)+(2\mbox{ XOR } 3)=3+2+1=6.

Sample Input 2

10
3 1 4 1 5 9 2 6 5 3

Sample Output 2

237

Sample Input 3

10
3 14 159 2653 58979 323846 2643383 27950288 419716939 9375105820

Sample Output 3

103715602

Print the sum modulo (10^9+7).


function main(arg) {
  var price = parseInt(arg)
  var result = false
  var max = 1000000

  for (var i100 = 0; i100 < max; i100++) {
    if (result) break
    for (var i101 = 0; i101 < max; i101++) {
      if (result) break
      for (var i102 = 0; i102 < max; i102++) {
        if (result) break
        for (var i103 = 0; i103 < max; i103++) {
          if (result) break
          for (var i104 = 0; i104 < max; i104++) {
            if (result) break
            for (var i105 = 0; i105 < max; i105++) {
              total =
                100 * i100 +
                101 * i101 +
                102 * i102 +
                103 * i103 +
                104 * i104 +
                105 * i105
              if (total === price) {
                result = true
                break
              }
            }
          }
        }
      }
    }
  }
  console.log(result ? 1 : 0)
}

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

Score: 300 points

Problem Statement

AtCoder Mart sells 1000000 of each of the six items below:

Riceballs, priced at 100 yen (the currency of Japan) each

Sandwiches, priced at 101 yen each

Cookies, priced at 102 yen each

Cakes, priced at 103 yen each

Candies, priced at 104 yen each

Computers, priced at 105 yen each

Takahashi wants to buy some of them that cost exactly X yen in total.
Determine whether this is possible.

(Ignore consumption tax.)

Constraints

1 \leq X \leq 100000

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

If it is possible to buy some set of items that cost exactly X yen in total, print 1; otherwise, print 0.

Sample Input 1

615

Sample Output 1

1

For example, we can buy one of each kind of item, which will cost 100+101+102+103+104+105=615 yen in total.

Sample Input 2

217

Sample Output 2

0

No set of items costs 217 yen in total.


function Main(input) {
  var ans = Math.floor(input);
  var flag = true;
  var yesKosu = 1;

  while (flag) {
    var yesLine = 100;
    yesLine *= yesKosu;
    if (ans < yesLine) {
      console.log('0');
      flag = false;
      break;
    }
    if (ans >= yesLine && ans <= yesLine + yesKosu * 5) {
      console.log('1');
      flag = false;
      break;
    }
    yesKosu++;
  }
}
Main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function Main(input) {
  var nums = input.split('\n');

  var keta = Math.floor(nums[0]);

  function product_Range(a, b) {
    var prd = a,
      i = a;

    while (i++ < b) {
      prd *= i;
    }
    return prd;
  }

  function combinations(n, r) {
    if (n == r) {
      return 1;
    } else {
      r = r < n - r ? n - r : r;
      return product_Range(r + 1, n) / product_Range(1, n - r);
    }
  }

  var ans = combinations(keta, keta - 3) - (keta - 3);

  console.log(ans);
}
Main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score: 400 points

Problem Statement

AtCoder Inc. has decided to lock the door of its office with a 3-digit PIN code.

The company has an N-digit lucky number, S. Takahashi, the president, will erase N-3 digits from S and concatenate the remaining 3 digits without changing the order to set the PIN code.

How many different PIN codes can he set this way?

Both the lucky number and the PIN code may begin with a 0.

Constraints

4 \leq N \leq 30000

S is a string of length N consisting of digits.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the number of different PIN codes Takahashi can set.

Sample Input 1

4
0224

Sample Output 1

3

Takahashi has the following options:

Erase the first digit of S and set 224.

Erase the second digit of S and set 024.

Erase the third digit of S and set 024.

Erase the fourth digit of S and set 022.

Thus, he can set three different PIN codes: 022, 024, and 224.

Sample Input 2

6
123123

Sample Output 2

17

Sample Input 3

19
3141592653589793238

Sample Output 3

329


"use strict";
var GET=(function(){function f(s){return new g(s);}function g(s){this._s=s.trim().split("\n");this._y=0;}g.prototype.a=function(f){var s=this._s, y=this._y, r;if(typeof s[y]==="string")s[y]=s[y].split(" ").reverse();r=s[y].pop();if(!s[y].length)this._y++;return f?r:+r;};g.prototype.l=function(f){var s=this._s[this._y++].split(" ");return f?s:s.map(a=>+a);};g.prototype.m=function(n,f){var r=this._s.slice(this._y,this._y+=n).map(a=>a.split(" "));return f?r:r.map(a=>a.map(a=>+a));};g.prototype.r=function(n,f){var r=this._s.slice(this._y,this._y+=n);return f?r:r.map(a=>+a);};return f;})();
var o=GET(require("fs").readFileSync("/dev/stdin","utf8"));
function xArray(v){var a=arguments,l=a.length,r="Array(a["+--l+"]).fill(0).map(x=>{return "+v+";})";while(--l)r="Array(a["+l+"]).fill(0).map(x=>"+r+")";return eval(r);}

console.log(main());
function main(){
  var n = o.a();
  var s = o.a(1);
  s = s.split("");
  for(var i = 0; i < s.length; i++){
    s[i] = String.fromCharCode((s[i].charCodeAt()-65+n)%26+65);
  }
  return s.join("");
}

Score : 200 points

Problem Statement

We have a string S consisting of uppercase English letters. Additionally, an integer N will be given.

Shift each character of S by N in alphabetical order (see below), and print the resulting string.

We assume that A follows Z. For example, shifting A by 2 results in C (A \to B \to C), and shifting Y by 3 results in B (Y \to Z \to A \to B).

Constraints

0 \leq N \leq 26

1 \leq |S| \leq 10^4

S consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the string resulting from shifting each character of S by N in alphabetical order.

Sample Input 1

2
ABCXYZ

Sample Output 1

CDEZAB

Note that A follows Z.

Sample Input 2

0
ABCXYZ

Sample Output 2

ABCXYZ

Sample Input 3

13
ABCDEFGHIJKLMNOPQRSTUVWXYZ

Sample Output 3

NOPQRSTUVWXYZABCDEFGHIJKLM


'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', function(inputStdin) {
    inputString += inputStdin;
});

process.stdin.on('end', function() {
    inputString = inputString.split('\n');
    main();
});

function readline() {
    return inputString[currentLine++];
}

// main funtion .. code start ..... ///
function main() {

    var T = parseInt(readline());
    var str = readline();

    var res1 = str.slice(0, Math.floor(T/2));
    var res2 = str.slice(T/2);

    if(str.length === 1 ) console.log('No');
    else console.log(res1 === res2 ? 'Yes': 'No');

}

Score : 200 points

Problem Statement

Given are a positive integer N and a string S of length N consisting of lowercase English letters.

Determine whether the string is a concatenation of two copies of some string.
That is, determine whether there is a string T such that S = T + T.

Constraints

1 \leq N \leq 100

S consists of lowercase English letters.

|S| = N

Input

Input is given from Standard Input in the following format:

N
S

Output

If S is a concatenation of two copies of some string, print Yes; otherwise, print No.

Sample Input 1

6
abcabc

Sample Output 1

Yes

Let T = abc, and S = T + T.

Sample Input 2

6
abcadc

Sample Output 2

No

Sample Input 3

1
z

Sample Output 3

No


function main(input) {
    var inputs = input.split('\n');
    var num = parseInt(inputs[0],10);
    var str = inputs[1];
    var strhalf = str.substring(0,num/2);
    if(str == (strhalf + strhalf))
        console.log('Yes');
    else
        console.log('No');
}

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


'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', function(inputStdin) {
    inputString += inputStdin;
});

process.stdin.on('end', function() {
    inputString = inputString.split('\n');
    main();
});

function readline() {
    return inputString[currentLine++];
}

// main funtion .. code start ..... ///
function main() {

    var T = parseInt(readline());
    var str = readline();

    var res1 = str.slice(0, Math.floor(T/2));
    var res2 = str.slice(T/2);

    if(str.length === 1) print('No');
    print(res1 === res2 ? 'Yes': 'No');
}


function Main(input) {
  var lines = input.split("\n").filter(v=>v!=='')
  var body = lines.slice(1)

  var n = +lines.slice(0,1)
  var poss = body.map(s=>s.split(' ').map(v=>+v))
  var cache = {}
  var sum = 0

  let diff = (x1,y1,x2,y2) => {
    var v = Math.sqrt(((x1-x2)**2) + ((y1-y2)**2))
    console.log({x1,y1,x2,y2,v})
    return v
  }

  let f = (past_poss,use_poss) => {
    if(use_poss.length == 0) {
      let d = 0;
      for(var i=1;i<past_poss.length;i++){
        var x = +past_poss[i-1][0]
        var y = +past_poss[i-1][1]
        var _x = +past_poss[i][0]
        var _y = +past_poss[i][1]
        sum += diff(x,y,_x,_y)
      }
      console.log({sum})
      return
    }
    use_poss.forEach(_pos=>{
      //sum += diff(x,y,_x,_y)
      f([...past_poss,_pos],use_poss.filter(__pos=>__pos.toString() != _pos.toString()))
    })
  }
  poss.forEach(_pos=>{
    f([_pos],poss.filter(__pos=>__pos.toString() != _pos.toString()))
  })
  var b = 1
  for(;n>0;n--){
    b *=  n
  }
  console.log(sum/b)
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 300 points

Problem Statement

There are N towns in a coordinate plane. Town i is located at coordinates (x_i, y_i). The distance between Town i and Town j is \sqrt{\left(x_i-x_j\right)^2+\left(y_i-y_j\right)^2}.

There are N! possible paths to visit all of these towns once. Let the length of a path be the distance covered when we start at the first town in the path, visit the second, third, \dots, towns, and arrive at the last town (assume that we travel in a straight line from a town to another). Compute the average length of these N! paths.

Constraints

2 \leq N \leq 8

-1000 \leq x_i \leq 1000

-1000 \leq y_i \leq 1000

\left(x_i, y_i\right) \neq \left(x_j, y_j\right) (if i \neq j)

(Added 21:12 JST) All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
:
x_N y_N

Output

Print the average length of the paths.
Your output will be judges as correct when the absolute difference from the judge's output is at most 10^{-6}.

Sample Input 1

3
0 0
1 0
0 1

Sample Output 1

2.2761423749

There are six paths to visit the towns: 1 → 2 → 3, 1 → 3 → 2, 2 → 1 → 3, 2 → 3 → 1, 3 → 1 → 2, and 3 → 2 → 1.

The length of the path 1 → 2 → 3 is \sqrt{\left(0-1\right)^2+\left(0-0\right)^2} + \sqrt{\left(1-0\right)^2+\left(0-1\right)^2} = 1+\sqrt{2}.

By calculating the lengths of the other paths in this way, we see that the average length of all routes is:

\frac{\left(1+\sqrt{2}\right)+\left(1+\sqrt{2}\right)+\left(2\right)+\left(1+\sqrt{2}\right)+\left(2\right)+\left(1+\sqrt{2}\right)}{6} = 2.276142...

Sample Input 2

2
-879 981
-866 890

Sample Output 2

91.9238815543

There are two paths to visit the towns: 1 → 2 and 2 → 1. These paths have the same length.

Sample Input 3

8
-406 10
512 859
494 362
-955 -475
128 553
-986 -885
763 77
449 310

Sample Output 3

7641.9817824387


function main(input) {
  var s = input[0]-0;
  console.log(Math.ceil(s/2));
}

main(require('fs').readFileSync('/dev/stdin', 'utf8').split("\n"))

Score : 100 points

Problem Statement

How many ways are there to choose two distinct positive integers totaling N, disregarding the order?

Constraints

1 \leq N \leq 10^6

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

4

Sample Output 1

1

There is only one way to choose two distinct integers totaling 4: to choose 1 and 3. (Choosing 3 and 1 is not considered different from this.)

Sample Input 2

999999

Sample Output 2

499999


"use strict";

const main = arg => {
    arg = arg.trim().split("\n");
    const N = parseInt(arg[0]);

    console.log(Math.ceil(N / 2) - 1);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


input = require('fs').readFileSync('/dev/stdin', 'utf8')
lines = input.split('\n')
N = lines.shift() * 1

bool = false
for(i=1; i<=9; i++) {
    d = N/i
    if (d <= 9 && d == ~~d) {
        bool = true
        break;
    }
}
console.log(bool ? 'Yes' : 'No')

Score : 200 points

Problem Statement

Having learned the multiplication table, Takahashi can multiply two integers between 1 and 9 (inclusive) together.

Given an integer N, determine whether N can be represented as the product of two integers between 1 and 9. If it can, print Yes; if it cannot, print No.

Constraints

1 \leq N \leq 100

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If N can be represented as the product of two integers between 1 and 9 (inclusive), print Yes; if it cannot, print No.

Sample Input 1

10

Sample Output 1

Yes

10 can be represented as, for example, 2 \times 5.

Sample Input 2

50

Sample Output 2

No

50 cannot be represented as the product of two integers between 1 and 9.

Sample Input 3

81

Sample Output 3

Yes


function Main(input) {
    input.trim().split("\n").forEach(line => {
        var nums = line.split(" ").map(i => parseInt(i));
        var a = nums[0];
        var b = nums[1];
        var x = nums[2];
        var tan;
        if (a * a * b / 2 === x) {
            tan = b / a;
        } else if (a * a * b / 2 < x) {
            tan = a * a / 2 / (a * b - x / a)
        } else {
            tan = 2 * x / a / b / b
        }

        console.log(tan, (360 + 90 - Math.atan(tan) * 180 / Math.PI) % 360);
    });
}

process.stdin.resume();
process.stdin.setEncoding("utf8");
var globalInput = '';
process.stdin.on('data', function(chunk) {
    globalInput += chunk;
})
process.stdin.on('end', function() {
    Main(globalInput)
})

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

Score : 400 points

Problem Statement

Takahashi has a water bottle with the shape of a rectangular prism whose base is a square of side a~\mathrm{cm} and whose height is b~\mathrm{cm}. (The thickness of the bottle can be ignored.)

We will pour x~\mathrm{cm}^3 of water into the bottle, and gradually tilt the bottle around one of the sides of the base.

When will the water be spilled? More formally, find the maximum angle in which we can tilt the bottle without spilling any water.

Constraints

All values in input are integers.

1 \leq a \leq 100

1 \leq b \leq 100

1 \leq x \leq a^2b

Input

Input is given from Standard Input in the following format:

a b x

Output

Print the maximum angle in which we can tilt the bottle without spilling any water, in degrees.
Your output will be judged as correct when the absolute or relative error from the judge's output is at most 10^{-6}.

Sample Input 1

2 2 4

Sample Output 1

45.0000000000

This bottle has a cubic shape, and it is half-full. The water gets spilled when we tilt the bottle more than 45 degrees.

Sample Input 2

12 21 10

Sample Output 2

89.7834636934

This bottle is almost empty. When the water gets spilled, the bottle is nearly horizontal.

Sample Input 3

3 1 8

Sample Output 3

4.2363947991

This bottle is almost full. When the water gets spilled, the bottle is still nearly vertical.


function main(input) {
    const args = input.split(' ');
    const A = parseInt(args[0], 10),
          B = parseInt(args[1], 10);
    const left = A - B * 2;
    if (left < 0) console.log(0);
    console.log(left);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 100 points

Problem Statement

The window of Takahashi's room has a width of A. There are two curtains hung over the window, each of which has a horizontal length of B. (Vertically, the curtains are long enough to cover the whole window.)

We will close the window so as to minimize the total horizontal length of the uncovered part of the window.
Find the total horizontal length of the uncovered parts of the window then.

Constraints

1 \leq A \leq 100

1 \leq B \leq 100

A and B are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the total horizontal length of the uncovered parts of the window.

Sample Input 1

12 4

Sample Output 1

4

We have a window with a horizontal length of 12, and two curtains, each of length 4, that cover both ends of the window, for example. The uncovered part has a horizontal length of 4.

Sample Input 2

20 15

Sample Output 2

0

If the window is completely covered, print 0.

Sample Input 3

20 30

Sample Output 3

0

Each curtain may be longer than the window.


var input = require("fs").readFileSync("/dev/stdin", "utf8").trim().split("\n");
var obj = {
  "list" : input, "index" : 0, "max" : input.length,
  "hasNext" : function(){return (this.index < this.max);},
  "next" : function(){
    if(!this.hasNext()){throw "NoSuchElementException:次に要素は無いよ";}
    var returnObj = this.list[this.index];
    this.index++;
    return returnObj;
  }
}
Main();
function next(){return obj.next();}
function nextInt(){return myconv(next(),1);}
function nextStrArray(){return myconv(next(),2);}//半角スペース分割
function nextIntArray(){return myconv(next(),4);}//半角スペース + 数値化
function nextCharArray(){return myconv(next(),6);}//1文字分割
function hasNext(){return obj.hasNext();}
function myout(t){console.log(t);}//標準出力
function myerr(t){console.error(t);}//標準エラー出力
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す　1:数値へ変換
//2:半角SPで分割 4:半角SPで分割し、数値配列へ
//6:1文字で分割  7:1文字で分割し、数値配列へ
//8:半角SPで結合 9:改行で結合 0:文字なしで結合
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map((a)=>Number(a));case 6:return i.split("");case 7:return i.split("").map((a)=>Number(a));case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}
function Main(){
  var one = nextIntArray();
  var N = one[0];
  var M = one[1];
  var L = one[2];
  var kyori = new Array(N);
  var max = Math.pow(10,15);
  for(var i = 0; i < N; i++){
    kyori[i] = new Array(N).fill(max);
    kyori[i][i] = 0;
  }
  var list = new Array(M);
  for(var i = 0; i < M; i++){
    list[i] = nextIntArray();
    kyori[list[i][0] - 1][list[i][1] - 1] = list[i][2];
    kyori[list[i][1] - 1][list[i][0] - 1] = list[i][2];
  }
  for(var k = 0; k < N; k++){
    for(var i = 0; i < N; i++){
      for(var j = 0; j < N; j++){
        if(kyori[i][j] > kyori[i][k] + kyori[k][j]){
           kyori[i][j] = kyori[i][k] + kyori[k][j];
        }
      }
    }
  }
  var count = new Array(N);
  for(var i = 0; i < N; i++){
    count[i] = new Array(N).fill(max);
    for(var j = 0; j < N; j++){
      if(kyori[i][j] <= L){
        count[i][j] = 1;
      }else{
        count[i][j] = max;
      }
    }
    count[i][i] = 0;
  }
  for(var k = 0; k < N; k++){
    for(var i = 0; i < N; i++){
      for(var j = 0; j < N; j++){
        if(count[i][j] > count[i][k] + count[k][j]){
           count[i][j] = count[i][k] + count[k][j];
        }
      }
    }
  }
  //myerr(kyori);
  //myerr(count);
  var Q = nextInt();
  var output = new Array(Q);
  for(var i = 0; i < Q; i++){
    var query = nextIntArray();
    query[0]--;
    query[1]--;
    var getCount = count[query[0]][query[1]];
    if(getCount >= max){
      getCount = 0;
    }
    output[i] = getCount - 1;
  }
  myout(myconv(output,9));
}

Score : 500 points

Problem Statement

There are N towns numbered 1 to N and M roads. The i-th road connects Town A_i and Town B_i bidirectionally and has a length of C_i.

Takahashi will travel between these towns by car, passing through these roads. The fuel tank of his car can contain at most L liters of fuel, and one liter of fuel is consumed for each unit distance traveled. When visiting a town while traveling, he can full the tank (or choose not to do so). Travel that results in the tank becoming empty halfway on the road cannot be done.

Process the following Q queries:

The tank is now full. Find the minimum number of times he needs to full his tank while traveling from Town s_i to Town t_i. If Town t_i is unreachable, print -1.

Constraints

All values in input are integers.

2 \leq N \leq 300

0 \leq M \leq \frac{N(N-1)}{2}

1 \leq L \leq 10^9

1 \leq A_i, B_i \leq N

A_i \neq B_i

\left(A_i, B_i\right) \neq \left(A_j, B_j\right) (if i \neq j)

\left(A_i, B_i\right) \neq \left(B_j, A_j\right) (if i \neq j)

1 \leq C_i \leq 10^9

1 \leq Q \leq N\left(N-1\right)

1 \leq s_i, t_i \leq N

s_i \neq t_i

\left(s_i, t_i\right) \neq \left(s_j, t_j\right) (if i \neq j)

Input

Input is given from Standard Input in the following format:

N M L
A_1 B_1 C_1
:
A_M B_M C_M
Q
s_1 t_1
:
s_Q t_Q

Output

Print Q lines.

The i-th line should contain the minimum number of times the tank needs to be fulled while traveling from Town s_i to Town t_i. If Town t_i is unreachable, the line should contain -1 instead.

Sample Input 1

3 2 5
1 2 3
2 3 3
2
3 2
1 3

Sample Output 1

0
1

To travel from Town 3 to Town 2, we can use the second road to reach Town 2 without fueling the tank on the way.

To travel from Town 1 to Town 3, we can first use the first road to get to Town 2, full the tank, and use the second road to reach Town 3.

Sample Input 2

4 0 1
1
2 1

Sample Output 2

-1

There may be no road at all.

Sample Input 3

5 4 4
1 2 2
2 3 2
3 4 3
4 5 2
20
2 1
3 1
4 1
5 1
1 2
3 2
4 2
5 2
1 3
2 3
4 3
5 3
1 4
2 4
3 4
5 4
1 5
2 5
3 5
4 5

Sample Output 3

0
0
1
2
0
0
1
2
0
0
0
1
1
1
0
0
2
2
1
0


function Main(input) {

    var data = input.split("\n")
    var n = parseInt(data[0]);
    var ans;
    if(n%2===0){
        ans = 1/2;
    }else{
        ans = (n+1)/2/n
    }

    console.log('%f\n',ans);
}
//（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 100 points

Problem Statement

Given is an integer N.

Takahashi chooses an integer a from the positive integers not greater than N with equal probability.

Find the probability that a is odd.

Constraints

1 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

Print the probability that a is odd.
Your output will be considered correct when its absolute or relative error from the judge's output is at most 10^{-6}.

Sample Input 1

4

Sample Output 1

0.5000000000

There are four positive integers not greater than 4: 1, 2, 3, and 4. Among them, we have two odd numbers: 1 and 3. Thus, the answer is \frac{2}{4} = 0.5.

Sample Input 2

5

Sample Output 2

0.6000000000

Sample Input 3

1

Sample Output 3

1.0000000000