jiahuimbzuai/CoQuIR huggingface dataset:
//  [java]
import java.math.BigInteger;
import java.util.Scanner;
public class Main {

	public static void main(String[] args) {
		try{
			Scanner sc = new Scanner(System.in);
			int N = sc.nextInt();
			int M = sc.nextInt();
			BigInteger A = new BigInteger(Math.min(N, M) + "");
			BigInteger B = new BigInteger(Math.max(N, M) + "");
			if(B.add(A.negate()).intValue() > 1){
				System.out.println(0);
			}else{
				BigInteger sub = new BigInteger((B.equals(A))? "2" : "1");
				BigInteger result = mult(A).multiply(mult(B)).multiply(sub).mod(new BigInteger("1000000007"));
				System.out.println(result.toString());
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	private static BigInteger mult(BigInteger x){
		BigInteger result = new BigInteger("1");
		while(x.intValue() > 1){
			result = result.multiply(x).mod(new BigInteger("1000000007"));
			x = x.add(new BigInteger("1").negate());
		}
		return result;
	}
}
//  [cpp]
#include<bits/stdc++.h>
#define FOR(i, a, b) for (int i = (a); i < (b); ++i)
#define REP(i, n) for (int i = 0; i < (n); ++i)
#define int long long
#define vec(a,n) vector<int> (a)((n))
#define Vec(a,n) vector<string> (a)((n))
using namespace std;
signed main(){
	int n,m,ans=1;
	cin >> n >> m;
	if(n == m){
		FOR(i,1,n+1){
			ans *= i;
			while(ans > 1000000007){
				ans -= 1000000007;
			}
		}
		ans *= ans*2;
	}else if(abs(n-m) == 1){
		FOR(i,1,n+1){
			ans *= i;
			while(ans > 1000000007){
				ans -= 1000000007;
			}
		}
		FOR(i,1,m+1){
			ans *= i;
			while(ans > 1000000007){
				ans -= 1000000007;
			}
		}
	}
	else{
		ans = 0;
	}
	while(ans >= 1000000007){
				ans -= 1000000007;
			}
	cout << ans << endl;
    return 0;
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;

long long pow2(long long x, long long n, int mod=0) {
  if (n == 0) return 1;
  if (mod) {
    if (n & 1) return x * pow2(x, n - 1, mod) % mod;
    long long y = pow2(x, n / 2, mod);
    return y * y % mod;
  } else {
    if (n & 1) return x * pow2(x, n - 1);
    long long y = pow2(x, n / 2);
    return y * y;
  }
}

int MOD = 1e9 + 7;
int U = 1e7;
vector<unsigned long long> fac(U + 1);
vector<unsigned long long> ifac(U + 1);
vector<unsigned long long> n_choose(U + 1);
void make_tables(int n=1e9, int p=MOD) {
  fac[0] = 1;
  for (int i = 0; i < U; i++) fac[i+1] = fac[i] * (i + 1) % p;
  ifac[U] = pow2(fac[U], p - 2, p);
  for (int i = U; i > 0; i--) ifac[i-1] = fac[i] * i % p;
  n_choose[0] = 1;
  for (int i = 0; i < U; i++) n_choose[i+1] = n_choose[i] * (n - i) % p;
  for (int i = 0; i < U + 1; i++) n_choose[i] = n_choose[i] * ifac[i] % p;
}

int mod_choose(int n, int r, int p=MOD) {
  if (r > n || r < 0) return 0;
  return fac[n] * ifac[r] % p * ifac[n-r] % p;
}

int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  make_tables();
  int n, m;
  cin >> n >> m;
  int ans;
  int d = abs(n - m);
  if (d >= 2) ans = 0;
  else if (d == 1) ans = fac[n] * fac[m] % MOD;
  else ans = fac[n] * fac[m] * 2 % MOD;
  cout << ans << '\n';
  return 0;
}
//  [cpp]
#include<iostream>
using namespace std;
typedef long long ll;

const int MAX = 10000000;
//何で割るのか
const int MOD = 1000000007;

ll fac[MAX], finv[MAX], inv[MAX];

// テーブルを作る前処理
void COMinit() {
    fac[0] = fac[1] = 1;
    finv[0] = finv[1] = 1;
    inv[1] = 1;
    for (int i = 2; i < MAX; i++){
        fac[i] = fac[i - 1] * i % MOD;
        inv[i] = MOD - inv[MOD%i] * (MOD / i) % MOD;
        finv[i] = finv[i - 1] * inv[i] % MOD;
    }
}

// 二項係数計算
ll COM(int n, int k){
    if (n < k) return 0;
    if (n < 0 || k < 0) return 0;
    return fac[n] * (finv[k] * finv[n - k] % MOD) % MOD;
}

int main(){
  // 前処理
  COMinit();
  int n,m;cin >> n >> m;
  if(n-m==1 or n-m==-1){
    cout << ((fac[n]%MOD)*fac[m])%MOD << endl;
  }else if(n==m){
    cout << (((fac[n]%MOD)*fac[m])%MOD*2)%MOD << endl;
  }else{
    cout << 0 << endl;
  }
}
//  [c]
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#define MAX(X, Y) (((X) > (Y))? (X) : (Y))
#define MIN(X, Y) (((X) < (Y))? (X) : (Y))
int compare_int(const void *a, const void *b){
  return *(long int*)b - *(long int*)a; // 大きい順
}
// 公約数
long int gcd(long int a, long int b){
  if(b == 0){
    return a;
  }else{
    return gcd(b, a % b);
  }
}
// 最小公倍数 = a * b / 最大公約数
// 公倍数
long int lcm(long int a, long int b){
  return a * b / gcd(a, b);
}



// min
int main(void){
  long long int n, m;
  long long int num;
  long long int ans = 1;

  scanf("%lld%lld", &n, &m);

  if(n - m > 1 || m - n > 1){
    printf("0\n");
    return 0;
  }else if(n == m){
    for(long int i = n; i > 0; i--){
      ans *= i;
      while(ans > 1000000007){
	ans -= 1000000007;
      }
    }
    for(long int i = m; i > 0; i--){
      ans *= i;
      while(ans > 1000000007){
	ans -= 1000000007;
      }
    }
    ans = ans * 2;
      while(ans > 1000000007){
	ans -= 1000000007;
      }
  }else{
    for(long int i = n; i > 0; i--){
      ans *= i;
      while(ans > 1000000007){
	ans -= 1000000007;
      }
    }
    for(long int i = m; i > 0; i--){
      ans *= i;
      while(ans > 1000000007){
	ans -= 1000000007;
      }
    }    
  }
  
  
  printf("%lld\n", ans);
  return 0;
}
//  [c]
#include <stdio.h>
#include <inttypes.h>

#define MOD_BY UINT32_C(1000000007)

uint32_t add(uint32_t a, uint32_t b) {
	return a + b - MOD_BY * (a + b >= MOD_BY);
}

uint32_t mul(uint32_t a, uint32_t b) {
	uint32_t r = 0;
	while (b) {
		if (b & 1) r = add(r, a);
		a = add(a, a);
		b >>= 1;
	}
	return r;
}

int main(void) {
	uint32_t N, M;
	if (scanf("%" SCNu32 "%" SCNu32, &N, &M) != 2) return 1;
	if (N == M || N == M + 1 || N + 1 == M) {
		uint32_t answer = 1;
		uint32_t i;
		for (i = 1; i <= N; i++) answer = mul(answer, i);
		for (i = 1; i <= M; i++) answer = mul(answer, i);
		if (N == M) answer = mul(answer, 2);
		printf("%" PRIu32 "\n", answer);
	} else {
		puts("0");
	}
	return 0;
}
//  [c]
#include<stdio.h>
#include<math.h>
int main()
{
long long int a,b,ans,mod,i,modp[200001];
  scanf("%lld %lld",&a,&b);
  mod=pow(10,9)+7;
  modp[0]=1;
  for(i=1;i<200001;++i)
  {
  modp[i]=(modp[i-1]*i)%mod;
  }
  ans=(modp[a]*modp[b])%mod;
  if(llabs(a-b)>1) printf("0");
  else if(a==b) printf("%lld",(ans*2)%mod);
  else printf("%lld",ans);
return 0;}
//  [javascript]
function Main(input) {
    input = input.split("\n");
    var line = input[0].split(" ");
    var dogs = parseInt(line[0]);
    var monks = parseInt(line[1]);
    var ans = 0;
    var dogsCount = 1;
    var monksCount = 1;
    var limit = 1E9+7;
    if(Math.abs(dogs-monks)>1){
        console.log(ans);
    } else {
        for(var i = 0; i<dogs; i++){
            dogsCount *= i+1;
            if(dogsCount>=limit){
                dogsCount %= limit;
            }
        }
        
//        console.log(dogsCount);
        ans = dogsCount;

        for(var i = 0; i<monks; i++){
            ans *= i+1;
            if(ans>=limit){
                ans %= limit;
            }
 //           console.log(i+" "+ans);
        }
        
        if(dogs===monks){
            ans*=2;
        }
        
        if(ans>=limit){
            ans %= limit;
        }
        
        console.log(ans);
//        console.log(dogsCount*dogsCount*2%limit);
    }
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
"use strict";


const main = arg => {
    arg = arg.trim().split("\n");
    const N = parseInt(arg[0].split(" ")[0]);
    const M = parseInt(arg[0].split(" ")[1]);
    
    // 差が2以上あると交互に並べられない
    if(Math.abs(N - M) > 1) {
        console.log(0);
        return;
    }
    
    const MOD = 1e9 + 7;
    let answer = 1;
    
    for(let i=1; i<=N; i++) {
        answer = (answer % MOD) * (i % MOD);
    }
    
    for(let i=1; i<=M; i++) {
        answer = (answer % MOD) * (i % MOD);
    }
    
    // 差が1のときは、組み合わせが1通り 例：犬猿犬猿, 猿犬猿犬
    // 差が0のときは、組み合わせが2通り 例：犬猿犬猿犬
    // それによって答えを2倍にするかどうか分ける
    console.log(answer * ((N == M) + 1) % MOD);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [go]
package main

import (
	"fmt"
	"log"
)

func main() {
	log.SetFlags(log.Lshortfile)
	var N, M int
	fmt.Scan(&N, &M)
	getFactInv()
	if abs(N-M) >= 2 {
		fmt.Println("0")
	} else if abs(N-M) == 1 {
		fmt.Println(p(N, N) * p(M, M) % MOD)
	} else if N == M {
		fmt.Println(p(N, N) * p(M, M) % MOD * 2 % MOD)
	} else {
		fmt.Println("0")
	}

}

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

const MAX = 2000010

var MOD int = 1000000007 // 素数
var fact [MAX]int        // 階乗
var factInv [MAX]int     // 階乗の逆元
var inv [MAX]int

func getFactInv() {
	// 最初に一度だけ実行
	inv[1], fact[0], factInv[0] = 1, 1, 1
	// nHkはn+k+1Ckとなるためn+kをとる
	var i int
	for i = 2; i < MAX; i++ {
		inv[i] = inv[MOD%i] * (MOD - MOD/i) % MOD
	}
	for i = 1; i < MAX; i++ {
		fact[i] = fact[i-1] * i % MOD
		factInv[i] = factInv[i-1] * inv[i] % MOD
	}
}

// 1 以上 N 以下の N 個の整数の中から，相異なる K 個の整数を選ぶパターンの数を C(N,K) と書きます．
func c(n, k int) int {
	if k < 0 || k > n {
		return 0
	}
	return fact[n] * factInv[k] % MOD * factInv[n-k] % MOD
}

// 1 以上 N 以下の N 個の整数の中から，相異なる K 個の整数を選び，順番に並べるパターンの数を P(N,K) と書きます．
// p(N, N)のときN!
func p(n, k int) int {
	if k < 0 || k > n {
		return 0
	}
	return fact[n] * factInv[n-k] % MOD
}

// 1 以上 N 以下の N 個の整数の中から，重複を許して K 個の整数を選ぶパターンの数を H(N,K) と書きます．
func h(n, k int) int {
	if n == 0 && k == 0 {
		return 1
	}
	if n == 0 {
		return 0
	}
	return c(n+k-1, k)
}
//  [go]
// Package main provides
//
// File:  c.go
// Author: ymiyamoto
//
// Created on Wed Jan 16 16:34:18 2019
//
package main

import "fmt"

const mod = 1e9 + 7

var dp = map[int]int{}

func fact(n int) int {
	if v, ok := dp[n]; ok {
		return v
	}
	dp[n] = (n * fact(n-1)) % mod
	return dp[n]
}

func main() {
	var N, M int
	fmt.Scan(&N, &M)

	dp[0] = 1
	if N == M {
		fmt.Println((2 * (fact(N) * fact(M)) % mod) % mod)
	} else if N-1 == M || N == M-1 {
		fmt.Println((fact(N) * fact(M)) % mod)
	} else {
		fmt.Println(0)
	}
}
//  [go]
package main

import "fmt"

const c = 1000000007

func fact(n int64) int64 {
	if n == 1 {
		return 1
	}
	return n * fact(n-1) % c
}

func solve(n, m int64) int64 {
	switch n {
	case m:
		return fact(n) * fact(m) * 2 % c
	case m + 1, m - 1:
		return fact(n) * fact(m) % c
	}
	return 0
}

func main() {
	var n, m int64
	fmt.Scan(&n, &m)
	fmt.Println(solve(n, m))
}
//  [ruby]
eval"N,M="+gets.split*?,;p'21'[N-M].to_i*[*1..N,*1..M].reduce{|x,y|x*y%D=10**9+7}%D
//  [ruby]
eval"N,M="+gets.split*?,;p'21'[(N-M).abs].to_i*[*1..N,*1..M].reduce{|x,y|x*y%D=10**9+7}%D
//  [ruby]
require "openssl"

N, M = gets.split.map(&:to_i).sort
Q = (10 ** 9) + 7
if (N - M).abs > 1
  puts 0
  exit
end

def f(n)
  t = 1.to_bn
 (1..n).inject(t) { |r,i| r.mod_mul(i, Q) }
end

begin
  r = f(N)
  if N == M
    ans = r.mod_mul(r, Q).mod_mul(2, Q)
  else
    ans = r.mod_mul(r.mod_mul(M, Q), Q)
  end
  raise RuntimeError if ans.zero?
  puts ans
rescue
  retry
end
//  [rust]
#[allow(unused_imports)]
use proconio::marker::{Bytes, Chars, Usize1};
use proconio::{fastout, input};
use std::cmp::{max, min};
#[fastout]
fn main() {
    input! {
        n: usize,
        m: usize,
    }
    let waru = 1_000_000_000 + 7;
    let mut ans = 0;
    let diff = max(n, m) - min(n, m);
    if diff == 0 {
        ans = 2 * factorial(n, waru) * factorial(m, waru) % waru;
    } else if diff == 1 {
        ans = factorial(n, waru) * factorial(m, waru) % waru;
    }
    println!("{}", ans);
}
fn factorial(a: usize, waru: usize) -> usize {
    if a < 2 {
        1
    } else {
        a * (factorial(a - 1, waru) % waru) % waru
    }
}
//  [swift]
import Foundation
import CoreFoundation

#if swift(>=4.0)
#else
extension String {
    func split(separator separator: Character) -> [String] {
        return self.characters.split(separator).map{String($0)}
    }
    var count: Int {
        return self.characters.count
    }
    func uppercased() -> String {
        return self.uppercaseString
    }
    func lowercased() -> String {
        return self.lowercaseString
    }
}
extension Array where Element: Comparable {
    func max() -> Element? {
        return self.maxElement()
    }
    func min() -> Element? {
        return self.minElement()
    }
    func sorted() -> Array {
        return self.sort()
    }
    mutating func sort() {
        self.sortInPlace()
    }
}
extension Array {
    mutating func swapAt(i: Int, _ j: Int) {
        swap(&self[i], &self[j])
    }
    func joined(separator separator: String = " ") -> String {
        return self.map{String($0)}.joinWithSeparator(separator)
    }
    func reversed() -> Array {
        return self.reverse()
    }
    mutating func reverse() {
        self = self.reversed()
    }
    func enumerated() -> EnumerateSequence<[Element]> {
        return self.enumerate()
    }
    init(repeating: Element, count: Int) {
        self.init(count: count, repeatedValue: repeating)
    }
}
func stride<T: Strideable>(from start: T, to end: T, by stride: T.Stride) -> StrideTo<T> {
    return start.stride(to: end, by: stride)
}
#endif
func readInt() -> Int? {
    return Int(readLine()!)
}
func readStringSplit(by separator: Character = " ") -> [String] {
    return readLine()!.split(separator: separator)
}
func readIntSplit(by separator: Character = " ") -> [Int] {
    return readLine()!.split(separator: separator).map{Int($0)!}
}
prefix operator * {}
prefix func * <T> (a: [T]) -> (T, T)          { return (a[0], a[1]) }
prefix func * <T> (a: [T]) -> (T, T, T)       { return (a[0], a[1], a[2]) }
prefix func * <T> (a: [T]) -> (T, T, T, T)    { return (a[0], a[1], a[2], a[3]) }
prefix func * <T> (a: [T]) -> (T, T, T, T, T) { return (a[0], a[1], a[2], a[3], a[4]) }
infix operator ** { associativity right precedence 155 }    // 右結合，乗除算より強くビットシフトより弱い
func **(lhs: Int, rhs: Int) -> Int {
    return (0..<rhs).reduce(1){i,_ in i*lhs}
}
func **(lhs: Int, rhs: Double) -> Double {
    return pow(Double(lhs), rhs)
}
//func gcd(x: Int, _ y: Int) -> Int {
//    return y>0 ? gcd(y, x%y) : x
//}
//func lcm(x: Int, _ y: Int) -> Int {
//    return x * y / gcd(x, y)
//}

/*************** テストスペース ***************/

//arr.sort{$0.0==$1.0 ? $0.1<$1.1 : $0.0<$1.0}  // タプル配列のソート

/*************** メインプログラム ***************/

func factorial(x:Int)->Int{return (1...x).reduce(1){$0*$1%1000000007}}
let (N, M) = *readIntSplit()
print(factorial(N)*factorial(M)*(N==M ? 2:abs(N-M)<2 ?1:0)%1000000007)
//  [python]
import numpy as np
import math
import sys
sys.setrecursionlimit(10000000)

def main():
    S = input()
    if S[0] == "S":
        print("Cloudy")
    elif S[0] == "C":
        print("Rainy")
    else:
        print("Sunny")


if __name__ == '__main__':
    main()
//  [python]
import numpy as np
S=input()
if S=='Sunny':
    print('Cloudy')
elif S=='Cloudy':
    print('Rainy')
else:
    print('Sunny')
//  [java]
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String str = sc.next();
		String s[] = {"Sunny","Cloudy","Rainy"};
		
		for (int i = 0 ; i < 3 ; i++) {
			if (i == 2) {
				System.out.println(s[0]);
				break;
			}
			if(str.equals(s[i])) {
				System.out.println(s[i + 1]);
				break;
			}
			
			
		}
		
		
		
	}	
}
//  [c]
#include<stdio.h>
int main()
{
	char s[7];

	scanf("%s",s);

	if(s[0]=='S')
		puts("Cloudy");
	else if(s[0]=='C')
		puts("Rainy");
	else
		puts("Sunny");
	return 0;
}
//  [c]
#include<stdio.h>
#include<string.h>
int main()
{
	char s[100];
	scanf("%s",s);
	
		if(s[0]=='S')
		{
			printf("Cloudy\n");
		}
		else if(s[0]=='C')
		{
			printf("Rainy\n");
		}
		else
		{
			printf("Sunny\n");
		}
	
}
//  [c]
#include<stdio.h>
int main(void)
{
    char S[10];
  
    scanf("%s",S);
    
    if(S[0]=='S') printf("Cloudy\n");
    else if(S[0]=='C') printf("Rainy\n");
    else printf("Sunny\n");
  
    return 0;
}
//  [javascript]
const main = (input) => {
  var s = input[0];
  var ans = "";
  switch(s){
    case "Sunny":
      ans = "Cloudy";
      break;
    case "Cloudy":
      ans = "Rainy";
      break;
    case "Rainy":
      ans = "Sunny";
      break;
  }
  console.log(ans);
}
main(require('fs').readFileSync('/dev/stdin', 'UTF-8').trim().split("\n"));
//  [javascript]
function Main(input){
  var S = input.trim();
  if(S === "Sunny"){
    console.log("Cloudy");
  }else if(S === "Cloudy"){
    console.log("Rainy");
  }else if(S === "Rainy"){
    console.log("Sunny");
  }
  
  


}
 
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
'use strict';
const main = input => {
  input = input[0];
  if (input == 'Sunny') console.log('Cloudy');
  if (input == 'Cloudy') console.log('Rainy');
  if (input == 'Rainy') console.log('Sunny');
}
main(require("fs").readFileSync("/dev/stdin", "utf8").split('\n'));
//  [go]
package main

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

var sc = bufio.NewScanner(os.Stdin)

func main() {
	sc.Split(bufio.ScanWords)

	s := nextStr()
	if s == "Sunny" {
		fmt.Println("Cloudy")
		return
	}
	if s == "Cloudy" {
		fmt.Println("Rainy")
		return
	}
	fmt.Println("Sunny")
}

// ---- readfunc
func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}
func nextStr() string {
	sc.Scan()
	return sc.Text()
}
//  [go]
package main

import (
	"fmt"
)

func main() {
	var s string
	fmt.Scan(&s)
	w := []string{"Sunny", "Cloudy", "Rainy"}
	n := 0
	for i, v := range w {
		if v == s {
			n = i
		}
	}
	if n == 2 {
		fmt.Println(w[0])
	} else {
		fmt.Println(w[n+1])
	}
}
//  [ruby]
s=gets.chomp
t=["Sunny","Cloudy","Rainy"]
3.times do |i|
  if s==t[i]
    puts t[(i+1)%3]
  end
end
//  [ruby]
ans = {"Sunny" => "Cloudy", "Cloudy" => "Rainy", "Rainy" => "Sunny"}
puts ans[gets.chomp]
//  [ruby]
#!/usr/bin/env ruby

require 'set'

class Hash
  def push(key, value)
    self[key] = [] if self[key] == nil
    self[key].push(value)
  end
end

class Array
  def lower_bound(value)
    left = -1;
    right = self.length;
    while left + 1 < right
      mid = left + (right - left) / 2;
      if self[mid] >= value
        right = mid
      else
        left = mid
      end
    end
    right
  end

  def unique
    res = [self.first]
    each_cons(2) do |a, b|
      if a != b
        res.push(b)
      end
    end
    res
  end
end

def get_ints
  gets.chomp.split.map(&:to_i)
end

def get_ints_minus_one
  get_ints.map { |x| x - 1 }
end

def get_int
  gets.chomp.to_i
end

S = gets.chomp

case S
when 'Sunny'
  puts 'Cloudy'
when 'Cloudy'
  puts 'Rainy'
when 'Rainy'
  puts 'Sunny'
end
//  [rust]
use std::io::Read;

fn main() {
    let mut buf = String::new();
    std::io::stdin().read_to_string(&mut buf).unwrap();

    let answer = solve(&buf);

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

fn solve(input: &str) -> String {
    let mut iterator = input.split_whitespace();

    let s = iterator.next().unwrap();

    if s == "Sunny" {
        return "Cloudy".to_string();
    }
    if s == "Cloudy" {
        return "Rainy".to_string();
    }
    return "Sunny".to_string();
}
//  [rust]
fn main() {
    let s: String = read_line_as_value();
    match s.as_str() {
        "Sunny" => println!("Cloudy"),
        "Cloudy" => println!("Rainy"),
        "Rainy" => println!("Sunny"),
        _ => println!("should not be called"),
    };
}

fn read_line_as_value<T: std::str::FromStr>() -> T {
    let mut input = String::new();
    let res = std::io::stdin().read_line(&mut input);
    if let Err(error) = res {
        panic!("io error at stdin.read_line: {}", error);
    };
    match input.trim().parse() {
        Ok(val) => val,
        _ => panic!("error while parsing input: {}", input)
    }
}
//  [rust]
use std::io;

fn main() {
    let mut w = String::new();

    io::stdin()
        .read_line(&mut w)
        .expect("Failed to read line");

    let w_str :&str = &w;

    match w_str {
        "Sunny\n" => println!("Cloudy"),
        "Cloudy\n" => println!("Rainy"),
        "Rainy\n"=> println!("Sunny"),
            _ => println!("retry enter!")
    }
}
//  [swift]
let s = readLine()!

let a = ["Sunny", "Cloudy", "Rainy"]

switch s {
  case "Sunny": print("Cloudy")
  case "Cloudy": print("Rainy")
  default: print("Sunny")
}
//  [swift]
let arr = readLine()!
let dic = ["Sunny": "Cloudy", "Cloudy": "Rainy", "Rainy": "Sunny"]
print(dic[arr]!)
//  [swift]
let S=readLine()!,R="Rainy"
print(S<R ?R:S>R ?"Cloudy":"Sunny")
//  [typescript]
import { createInterface } from 'readline';

const main = (lines: string[]) => {
  console.log(solve(lines));
};

export const solve = (lines: string[]): string => {
  const S = parseLines(lines);

  if (S === 'Sunny') {
    return 'Cloudy';
  }
  if (S === 'Cloudy') {
    return 'Rainy';
  }

  return 'Sunny';
};

const parseLines = (lines: string[]) => {
  const obj = lines[0];
  debug(obj);
  return obj;
};

const debug = (message?: any, ...optionalParams: any[]) => {
  if (!!process.env.LOCAL_DEBUG) {
    console.log(message, ...optionalParams);
  }
};

if (!process.env.LOCAL_DEBUG) {
  const { stdin: input, stdout: output } = process;
  input.resume();
  input.setEncoding('utf8');
  const lines: string[] = [];
  createInterface({ input, output })
    .on('line', line => lines.push(line))
    .on('close', () => main(lines));
}
//  [typescript]
import * as fs from 'fs';

//in
//
//out
//
const main = (inp: string) => {
    const weather: { [s: string]: string } = {
        Sunny: 'Cloudy',
        Cloudy: 'Rainy',
        Rainy: 'Sunny'
    };

    console.log(weather[inp]);

};

main(fs.readFileSync('/dev/stdin', 'utf8').trim());
//  [typescript]
import * as fs from "fs";

const input = (fs.readFileSync("/dev/stdin", "utf8") as string).split("\n");
//const n = +input[0];
//const a = [];
//for(let i=0;i<n;i++){
//	a.push(input[i+1].split(" ").map((x:string):number=>+x));
//}

//const [n, m] = input[0].split(" ").map((x: string): number => +x);
//const a = input[1].split(" ").map((x: string): number => +x);

function compareFunc(a, b){
    return a-b;
}

const s: string = input[0];

if(s === 'Sunny'){
    console.log('Cloudy');
}else if(s === 'Cloudy'){
    console.log('Rainy');
}else{
    console.log('Sunny');
}
//  [python]
a=0
n=int(input())
num=list(map(int, input().split()))
for i in range(n):
    for j in range(i+1,n,1):
        a+=num[i]*num[j]
print(a)
//  [python]
N = int(input())
D = list(map(int, input().split()))

ans = 0

for i in range(N-1):
    for j in range(i+1,N,1):
        ans += D[i] * D[j]

print(ans)
//  [python]
tako=int(input())
takolist=list(map(int, input().split()))

hp=0
for i in range(tako-1):
  for j in range(i+1,tako):
    hp=takolist[i]*takolist[j]+hp

print(hp)
//  [python]
import sys
from fractions import gcd
from functools import reduce
from itertools import combinations
from random import random

import numpy as np

sys.setrecursionlimit(200000)


class Solver:
    def __init__(self):
        pass

    def input(self):
        """
            faster input function than builtin stdin.
        """
        return sys.stdin.readline()[:-1]

    def ii(self, t: type = int):
        """
            input single value.
        """
        return t(self.input())

    def il(self, t: type = int):
        """
            input single line.
        """
        return list(map(t, self.input().split()))

    def imi(self, N: int, t: type = int):
        return [self.ii(t) for _ in range(N)]

    def iml(self, N: int, t: type = int):
        return [self.il(t) for _ in range(N)]

    def solve(self):
        N = self.ii()
        d = self.il()
        ans = 0
        for x, y in combinations(d, 2):
            ans += x * y
        return ans


if __name__ == "__main__":
    solver = Solver()
    print(solver.solve())
//  [python]
#gcdは3.4.3だとfractionsにある
from fractions import gcd

from math import factorial as f

from math import ceil,floor,sqrt

from sys import exit

from copy import deepcopy
import numpy as np

import bisect
import re


ii = lambda : int(input())
mi = lambda : map(int,input().split())
li = lambda : list(map(int,input().split()))



def main():
    n = ii()
    a = li()

    s = sum(a)

    ans = 0

    for i in a:
        ans+=(s-i)*i
    
    print(ans//2)


main()
//  [python]
import numpy as np
import math
import sys
sys.setrecursionlimit(10000000)

def main():
    N = int(input())
    D = [int(c) for c in input().split()]
    num = 0
    for i in range(len(D)):
        for j in range(i + 1, len(D)):
            num += D[i] * D[j]
    print(num)
    
            
        


if __name__ == '__main__':
    main()
//  [java]
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

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

    static class BTAKOYAKIFESTIVAL2019 {
        public void solve(int testNumber, FastReader s, PrintWriter out) {
            int n = s.nextInt();
            int[] arr = s.nextIntArray(n);
            int ans = 0;
            int sumTillNow = 0;
            for (int i = 0; i < n; i++) {
                ans += (arr[i] * sumTillNow);
                sumTillNow += arr[i];
            }
            out.println(ans);
        }

    }

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

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

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

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

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

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

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

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

        }

    }
}
//  [java]
import java.io.*;
import java.util.*;

public class Main {
  public static void main(String[] args) {
    FastScanner fs = new FastScanner();

    int N = fs.nextInt();
    int[] D = new int[N];
    for (int i = 0; i < N; i++) D[i] = fs.nextInt();
    int ans = 0;
    for (int i = 0; i < N; i++)
      for (int j = 0; j < i; j++) ans += D[i] * D[j];
    System.out.println(ans);
  }
}

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

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

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

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

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

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

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

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

  public double nextDouble() {
    return Double.parseDouble(next());
  }
}
//  [java]
import java.util.Scanner;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = Integer.parseInt(sc.nextLine());
        String str  = sc.nextLine();
        String[] astr = str.split(" "); //状況に合わせて
        int[] in_data = Stream.of(astr).mapToInt(x->{
            try{
                return Integer.parseInt(x);
            }
            catch(Exception e){
                e.printStackTrace();
            }
            return 0;
        }).toArray();
        sc.close();
        int ans =0;

        for(int i=0;i<in_data.length;i++){
            for(int j =i+1;j<in_data.length;j++){
                ans += in_data[i] * in_data[j];
            }
        }
        System.out.println(ans);
    }
}
//  [java]
import java.util.*;

class Main{
	public static void main(String[] $){
		Scanner s=new Scanner(System.in);
		int n=s.nextInt();
		int[]a=new int[n];
		Arrays.setAll(a,i->s.nextInt());

		long r=0;
		for(int i=0;i<n;++i)
			for(int j=i+1;j<n;++j)
				r+=a[i]*a[j];
		System.out.println(r);
	}
}
//  [java]
import java.util.Scanner;
import java.util.stream.IntStream;

public class Main {

	public static void main(String[] args) {
		try (Scanner scanner = new Scanner(System.in)) {
			int n = scanner.nextInt();
			int[] d = new int[n];
			IntStream.range(0, n).forEach(i -> d[i] = scanner.nextInt());
			System.out.println(
					IntStream.range(0, n - 1).map(i -> IntStream.range(i + 1, n).map(j -> d[i] * d[j]).sum()).sum());
		}
	}
}
//  [cpp]
#include <stdio.h>

#define MAXN 50
int Tako[MAXN];

int main()
{
	int N;
	scanf("%d", &N);

	for (int n = 0; n < N; n++)
		scanf("%d", &Tako[n]);

	int Result = 0;
	for (int n = 0; n < N; n++)
		for (int j = n + 1; j < N; j++)
			Result += Tako[n] * Tako[j];
	
	printf("%d", Result);
	return 0;
}
//  [cpp]
#include<stdio.h> 
using namespace std;

int main() {
	int n,d[100];
	scanf("%d", &n);
	int i0 = 0; long result = 0;
	for(; i0<n; i0++) {scanf("%d", &d[i0]);}
	for(int i = 0; i < i0-1;i++){
		for(int j = i+1; j < i0;j++){
			result += d[i]*d[j];
		}
	}
	printf("%d", result);
	return 0;
}
//  [cpp]
#include<stdio.h>
int main()
{
	int n,d[100];
	int i,j,sum;
	scanf("%d",&n);
	for(i=0;i<n;i++){
		scanf("%d",&d[i]);
	}
	sum=0;
	for(i=0;i<n-1;i++){
		for(j=i+1;j<n;j++){
			sum+=d[i]*d[j];
		}
	}
	printf("%d",sum);
	return 0;
}
//  [cpp]
#include <bits/stdc++.h>
#include <boost/foreach.hpp>
using namespace std;
#define pi 2*asin(1.0)
#define MAX 10000000
#define MOD 1000000007
#define _GLIBCXX_DEBUG
 
vector<long> fac(MAX);
vector<long> finv(MAX);
vector<long> inv(MAX);
vector<long> Primelist;
//template functions
/////////////////////////
void Prinit(){
long PR=10000001;
vector<long> P(PR,0);
for(long i=2;i*i<PR;i++){
    if(P.at(i)==0){
        long j=i;
      j+=i;
        while(j<PR){
            P.at(j)=1;
             j+=i;         
        }
    }
}

for(long i=2;i*i<PR;i++){//Primelist.size()=446
    if(P.at(i)==0){
        Primelist.push_back(i);
    }
}
}

void Cominit(){
  fac.at(0)=fac.at(1)=1;
  finv.at(0)=finv.at(1)=1;
  inv.at(1)=1;
  for(long i=2;i<MAX;i++){
      fac.at(i)=(fac.at(i-1)*i)%MOD;
      inv.at(i)=MOD-inv.at(MOD%i)*(MOD/i)%MOD;
      finv.at(i)=finv.at(i-1)*inv.at(i)%MOD;
  }
}

long facComb(long N,long M){// nCm%
if(N<M) return 0;
if(N<0||M<0) return 0;
return fac.at(N)*(finv.at(M)*finv.at(N-M)%MOD)%MOD;
}

long Comb(long N,long M){// nCm
long ans=1;
for(long i=N;i>N-M;i--){
    ans=ans*i;
}
for(long i=M;i>0;i--){
    ans=ans/i;
}
return ans;
}

long Perm(long N,long M){// nPm
long ans=1;
for(long i=N;i>N-M;i--){
    ans=ans*i;
}
return ans;
}

long GCM(long A,long B){
            long W,r;
    if(A<B){

        W=B;
        B=A;
        A=W;
    }
    while(A%B!=0){
        r=A%B;
        A=B;
        B=r;
    }
    return B;
}
long LCM(long A,long B){
    return (A*B)/GCM(A,B);
}

long upDiv(long a,long b){
  return (a+b-1)/b;
}

long strtolong(string str){
istringstream ss;
ss=istringstream(str);
long num;
ss>>num;
return num;
}

long chartolong(char ch){
long num;
num=ch-'0';
return num;
}

string longtostr(long N){
    string str;
    str=to_string(N);
    return str;
}







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


//Answer


int main() {
long N,ans=0;
cin>>N;
vector<long> d(N);
for(long i=0;i<N;i++){
cin>>d.at(i);
}
for(long i=0;i<N;i++){
    for(long j=i+1;j<N;j++){
        ans+=d.at(i)*d.at(j);
    }
}
cout<<ans<<endl;



}
//  [c]
#include<stdio.h>
int main()
{
     int i,n,j,ara[100],count,sum=0;
     scanf("%d",&n);
     for(i=0;i<n;i++)
     {
          scanf("%d",&ara[i]);
     }
     for(i=0;i<n;i++)
     {
          for(j=i+1;j<n;j++)
          {
              count=ara[i]*ara[j];
              sum=count+sum;
          }
     }
     printf("%d\n",sum);
}
//  [c]
#include<stdio.h>
int main()
  {
  int N,d[N],S,i,j;
  scanf("%d",&N);
  for(i=0;i<N;i++)
    {
    scanf("%d",&d[i]);
    }
  S=0;
  for(i=0;i<N;i++)
    {
    for(j=i;j<N;j++)
      {
       S=S+d[i]*d[j+1];
      }
    }
  printf("%d",S);
  return 0;
  }
//  [c]
#include<stdio.h>
int main()
{
   

    int N;
    
    // 整数の入力
    scanf("%d",&N);
  
  	int i=0;
  	int d[N];
  	for(i=0;i<N;i++){
		scanf("%d", &d[i]);
    }
  int t=0;
  int ans = 0;
  int num = 0;
  for(i=0;i<N;i++){
	for(t=i+1;t<N;t++){
		num = d[i]*d[t];
      	ans = ans + num;
    	}
    }
    // 文字列の入力
    printf("%d",ans);
    return 0;
}
//  [c]
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <limits.h>
#include <stdbool.h>

#define rep(i, n) for(int i=0; i<(n); ++i)
#define max  200001

//qsort(str, n, sizeof(int), up_comp);
int up_comp(const void *a, const void *b){return *(int*)a - *(int*)b;}
int down_comp(const void *a, const void *b){return *(int*)b - *(int*)a;}
int int_sort( const void * a , const void * b ) {return strcmp(( char * )a , ( char * )b );}
int count_digit(int a){int i=0;while(a!=0){a=a/10;i++;}return i;}
int euclid( int a, int b ){int temp;if(a<b){temp=a;a=b;b=temp;}if(b<1)return -1;if(a%b==0) return b;return euclid(b,a%b);}

int main(void){
 
    int n, d[50];
    int sum=0;
    
    scanf("%d", &n);
    rep(i, n){
        scanf("%d", &d[i]);
    }
    
    rep(i, n-1){
        for (int j=i+1; j<n; j++) {
            sum+=d[i]*d[j];
        }
    }
    
    printf("%d", sum);
    
    return 0;
}
//  [c]
#include <stdio.h>

int main(void)
{
    int n=0;
    int d[51]={};
    long sum=0;
    scanf("%d",&n);
    for(int i=0;i<n;i++) scanf("%d",&d[i]);
    for(int i=1;i<n;i++){
        for(int j=0;j<i;j++){
            sum+=d[i]*d[j];
        }
    }
    printf("%ld",sum);
    return 0;
}
//  [c]
#include<stdio.h>
int main(void)
{
    int n,d[50],i,j,sum = 0;
    scanf("%d",&n);
    for(i = 0 ; i < n ; i++)
    {
        scanf("%d",&d[i]);
    }
    for(i = 0; i < n - 1 ; i++)
    {
        for(j = i + 1 ; j < n ; j++)
        {
            sum += d[i] * d[j];
        }
    }
    printf("%d\n",sum);
    return 0;
}
//  [javascript]
function Main(input) {
	// 1行目がinput[0], 2行目がinput[1], …に入る
	input = input.split("\n");
	inputN = parseInt(input[0]);
	inputD = input[1].split(" ");
	// temp = inputN * (inputN -1) / 2

	temp = 0;
	for(var i=0;i < inputD.length;i++){
		temp2 = 0;
		for(var j=i+1;j < inputD.length;j++){
			temp2 += parseInt(inputD[j]);
		}
		temp += parseInt(inputD[i]) * temp2;
	}
	console.log(temp);
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
// inputに入力データ全体が入る
function Main(input) {
  var input = input.split('\n');
  const n = Number(input[0])
  const ocps = input[1].split(' ').map(ocp => Number(ocp));
  var r = 0;
  for (var i = 0; i < n; i++) {
    for (var j = i+1; j < n; j++) {
      r += ocps[i] * ocps[j]
    }
  }
  console.log(r)
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
function Main(input){
  input = input.split("\n");
  inputStr = input[0].split(" ");
  const N = Number.parseInt(inputStr[0]);
  inputStr = input[1].split(" ");
  var D = inputStr.map(inputStr => Number.parseInt(inputStr));
  //計算処理
  var ans = 0;
  for(var i=0 ; i<N-1 ; i++){
    for(var j=i+1 ; j<N ; j++ ){
      ans += D[i] * D[j];
    }
  }
  console.log(ans);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
module.exports=function(t){var e={};function r(n){if(e[n])return e[n].exports;var i=e[n]={i:n,l:!1,exports:{}};return t[n].call(i.exports,i,i.exports,r),i.l=!0,i.exports}return r.m=t,r.c=e,r.d=function(t,e,n){r.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},r.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r.t=function(t,e){if(1&e&&(t=r(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var i in t)r.d(n,i,function(e){return t[e]}.bind(null,i));return n},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="",r(r.s=0)}([function(t,e,r){"use strict";var n=r(1);r(2)(n.readFileSync("/dev/stdin","utf8"))},function(t,e){t.exports=require("fs")},function(t,e,r){"use strict";var n=r(3),i=r(5);t.exports=function(t){var e=new n(t);i(e)}},function(t,e,r){"use strict";var n=r(4);t.exports=class{constructor(t){var e=t.trim().split(/\s+/g);this.inp=new n(e)}inr(){return this.inp.deq()}in(){return parseInt(this.inp.deq(),10)}fin(){this.inp.clear()}}},function(t,e,r){"use strict";t.exports=class{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];this.size=t.length,this.items=t,this.ind=0}enq(t){this.size+=1,this.items.push(t)}deq(){var t=this.items[this.ind];return this.size-=1,this.ind+=1,t}clear(){this.items=[],this.size=0,this.ind=0}}},function(t,e,r){"use strict";t.exports=function(t){for(var e=t.in(),r=new Array(e),n=0;n<e;n++)r[n]=t.in();for(var i=0,o=0;o<e;o++)for(var s=e-1;s>o;s--)i+=r[o]*r[s];console.log(i)}}]);
//  [javascript]
function Main(arg) {
 
    var N = arg.split("\n")[0]-0;
    var d = arg.split("\n")[1].split(" ").map(v => v-0);
 
    var ans = 0;

    for (var i = 0; i < N - 1; i++){
        for (var j = i+1; j < N; j++){
            ans += d[i] * d[j];
        }
    }

    console.log(ans)

    return;
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
'use strict';

const testcase = null;

function main(input) {
    const n = parseInt(input.shift());
    var total = 0;
    var ds = [];
    for (var i = 0; i < n; i++) {
        const d = parseInt(input.shift());
        for (var v of ds) {
            total += d * v;
        }
        ds.push(d);
    }
    console.log(total);
}

if (process.argv[1] == __filename) {
    const input = testcase
        || require('fs')
            .readFileSync('/dev/stdin', 'utf-8');
    main(input.split(/\s/));
}
//  [go]
package main

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

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

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

	sc := bufio.NewScanner(r)
	sc.Buffer(buf, maxBufSize)
	sc.Split(bufio.ScanWords) // bufio.ScanLines
	n := scanInt(sc)
	ds := make([]int, 0, n)
	for i := 0; i < n; i++ {
		ds = append(ds, scanInt(sc))
	}
	return n, ds
}

func resolve(n int, ds []int) int {
	sum := 0
	for i := 0; i < n; i++ {
		for j := i + 1; j < n; j++ {
			sum += ds[i] * ds[j]
		}
	}
	return sum
}

// snip-scan-funcs
func scanInt(sc *bufio.Scanner) int {
	sc.Scan()
	i, _ := strconv.Atoi(sc.Text())
	return int(i)
}
//  [go]
package main
 
import (
  "bufio"
  "fmt"
  "os"
  "strconv"
)
 
var sc = bufio.NewScanner(os.Stdin)

func next() int {
  sc.Scan()
  i, _ := strconv.Atoi(sc.Text())
  return i
}

func main() {
  sc.Split(bufio.ScanWords)
  n := next()
  tako := make([]int, n, n)
  takoSum := 0  // たこ焼きn種の回復量の和
  ans := 0 // 答え

  for i := 0; i < n; i++ {
    tako[i] = next()
    takoSum += tako[i]
  }
  
  for i := 0; i < n; i++ {
    ans += (takoSum - tako[i]) * tako[i]
  }
  // この時点だとあるたこ焼きの組は2回数えられているので2で割る
  ans /= 2
  fmt.Println(ans)
}
//  [go]
package main

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

var sc = bufio.NewScanner(os.Stdin)
var out = bufio.NewWriter(os.Stdout)

func next() string {
	sc.Scan()
	return sc.Text()
}
func nextInt() int {
	a, _ := strconv.Atoi(next())
	return a
}
func nextInts(n int) []int {
	ret := make([]int, n)
	for i := 0; i < n; i++ {
		ret[i] = nextInt()
	}
	return ret
}

//var done []bool = make([]bool, 10)
//var memo []int = make([]int, 10)

//func fib(n int) int {
//	fmt.Println(n)
//	if n == 0 {
//		return 0
//	}
//	if n == 1 {
//		return 1
//	}
//	if done[n] {
//		fmt.Println("done" + fmt.Sprint(n))
//		return memo[n]
//	}
//	done[n] = true
//	memo[n] = fib(n-1) + fib(n-2)
//	return memo[n]
//}

var m map[string]int = make(map[string]int)
var mInt map[int]int = make(map[int]int)

//var dp []int = make([]int, n)

//func fib(n int) int {
//	dp[0] = 0
//	dp[1] = 1
//	for i := 2; i <= n; i++ {
//		dp[i] = dp[i-1] + dp[i-2]
//	}
//	return dp[n]
//}

func main() {
	sc.Split(bufio.ScanWords)
	defer out.Flush() // !!!!coution!!!! you must use Fprint(out, ) not Print()
	n := nextInt()
	ns := nextInts(n)

	sort.Ints(ns)
	di := 0
	for i := 0; i < n-1; i++ {
		for j := i + 1; j < n; j++ {
			di += ns[i] * ns[j]
			//	fmt.Print(fmt.Sprint(ns[i]))
			//	fmt.Println(fmt.Sprint(ns[j]))
		}
	}
	fmt.Fprint(out, di)
}
//  [go]
package main

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

var sc *bufio.Scanner = func() *bufio.Scanner {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	return sc
}()

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}
func nextInts(n int) []int {
	ints := make([]int, n)
	for i := 0; i < n; i++ {
		ints[i] = nextInt()
	}
	return ints
}
func sum(takoyakis []int) (total int) {
	n := len(takoyakis)
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			if j <= i {
				continue
			}
			total += takoyakis[i] * takoyakis[j]
		}
	}
	return
}

func main() {
	n := nextInt()
	ints := nextInts(n)
	total := sum(ints)
	fmt.Println(total)
}
//  [go]
package main

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

func main() {
	var n int
	_, _ = fmt.Scan(&n)
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	d := strings.Split(scanner.Text(), " ")
	foods := make([]int, 4096)
	
	for index, str := range d {
		foods[index], _ = strconv.Atoi(str)
	}
	
	sum := 0
	
	for index, num := range foods {
		for index2, num2 := range foods {
			if index != index2 {
				sum += num * num2
			}
		}
	}
	
	fmt.Println(sum / 2)
}
//  [ruby]
# coding: utf-8
#ABC143B_TAKOYAKI2019.rb
n = gets.to_i
d = gets.split.map(&:to_i)

idx1 = 0
comb = []
ans = 0
while idx1 < n-1
  idx2 = idx1 + 1
  while idx2 < n
    ans +=  d[idx1]*d[idx2]
    idx2 += 1
  end
  idx1 += 1
end
puts ans
//  [ruby]
_n = gets.to_i
d = gets.split.map(&:to_i)

sum = d.combination(2).to_a
ans = 0

sum.each do |i|
  ans += i[0]*i[1]
end

puts ans
//  [ruby]
=begin
1, 受け取った数値を配列にし、多重ループして i * jを求める
2, 求めたi*jをans に足して出力
=end

gets
num_i = gets.split.map(&:to_i)
num_j = num_i.map(&:to_i)
ans = 0

num_i.each{|i|
  num_j.shift()
  num_j.each{|j|
    ans += i * j
  }
}

puts ans
//  [ruby]
n = gets.to_i
ary = gets.split.map(&:to_i)
sum = ary.inject(:+)
ans = 0

n.times do |i|
  sum = sum - ary[i]
  ans += ary[i] * sum
end

puts ans
//  [ruby]
n = gets.to_i
d = gets.split.map(&:to_i)
ans = 0
d.combination(2).each do |c|
  ans += c[0] * c[1]
end
puts ans
//  [ruby]
n = gets.chomp.to_i
d = gets.chomp.split(" ").map(&:to_i)
kaihuku = 0
d.permutation(2) do |i,j|
    kaihuku += i * j
end
puts kaihuku / 2
//  [rust]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

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

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

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

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

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

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

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

fn main(){

    input!{
        n: usize,
        d: [usize;n],
    }

    let mut sum = 0;

    for i in 0..n{
        for j in i+1..n{
            sum += d[i]*d[j];
        }
    }

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