jiahuimbzuai/CoQuIR huggingface dataset:
//  [cpp]
#include<bits/stdc++.h>
//#include<pair>
using namespace std;

typedef long long ll;
typedef int ii;
//typedef vector<ll> vi;

#define INF 1000000007

#define pi 3.141592654

#define T while(t--)
#define for2(i,a,b) for(i=a;i>=b;i--)
#define for3(i,a,b) for(i=a;i<=b;i=i+2)
#define for1(i,a,b) for(i=a;i<=b;i++)
#define pb push_back
#define mp make_pair

#include<sstream>

#define si set<ll>
#define se multiset<ll>

typedef long double ld;

typedef vector<ll> vi;

#define bb(arr,nn,xx) upper_bound(arr,arr+nn,xx)-arr
#define aa(arra,nna,xxa) lower_bound(arra,arra+nna,xxa)-arra

#define all(v) sort(v.begin(),v.end())
 
#define all1(v) sort(v.rbegin(),v.rend())

ii main()
{

    ios::sync_with_stdio(0);
    cin.tie(0);

    ll n,i,j; cin>>n; vi v; ll x;
    
    for1(i,1,n)
    {
    
        cin>>x;
       
        v.pb(x);
        
    }
    
    ll sum1=0; ll sum=0;
    
    for2(i,n-1,1)
    {
    
        sum1+=v[i];
        
        sum+=v[i-1]*sum1;
        
    }
    
    
   
    cout<<sum%(INF)<<"\n";
    
}
//  [c]
#include <ctype.h>
#include <float.h>
#include <inttypes.h>
#include <limits.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <math.h>
#ifdef __cplusplus
#include <bits/stdc++.h>
#endif
#pragma GCC target("avx2")
#pragma GCC optimize("O3")
//#pragma GCC optimize("unroll-loops")

//char rbuf[]; int rbufl;
//#define getchar() rbuf[rbufl++]
#define getchar getchar_unlocked
#define putchar putchar_unlocked
int32_t nextint(void){ char c=getchar(); while(c!='-'&&(c<'0'||'9'<c)) c=getchar(); bool s=false; if(c=='-'){s=true;c=getchar();} uint32_t x=0; while('0'<=c && c<='9'){ x=x*10+c-'0'; c=getchar(); } return s?-x:x; }
int64_t nextlong(void){ char c=getchar(); while(c!='-'&&(c<'0'||'9'<c)) c=getchar(); int s=0; if(c=='-'){s=1;c=getchar();} uint64_t x=0; while('0'<=c && c<='9'){ x=x*10+c-'0'; c=getchar(); } return s?-x:x; }
uint32_t nextstr(char *s){ char c=getchar(); while(c==' '||c=='\n') c=getchar(); uint32_t len=0; while(c!=' '&&c!='\n'){ *s++=c; len++; c=getchar(); } *s='\0'; return len; }
void printint(int32_t x){ if(x<0){x=-x; putchar('-');}else if(x==0){putchar('0');} int d=0; char s[10]; while(x){ s[d]='0'+x%10; x/=10; d++; } for (int i=d-1; i>=0; i--) putchar(s[i]); putchar('\n'); }
void rsorta_d32(void *base, const int count, const int size, const int index){
	typedef int32_t rsort_t;
	rsort_t (*a)[size] = (rsort_t(*)[size])base;
	rsort_t (*b)[size] = (rsort_t(*)[size])malloc(count*size*sizeof(rsort_t));
	int c[0x100];
	for(int k=0; k<4; k++){
		memset(c, 0, sizeof(c)); for(int i=0; i<count; i++){ c[(a[i][index]>>(k<<3))&0xFF]++; } for(int i=1; i<0x100; i++) c[i]+=c[i-1]; for(int i=count-1; i>=0; i--){ int to=--c[(a[i][index]>>(k<<3))&0xFF]; for(int j=0; j<size; j++){ b[to][j]=a[i][j]; } }{rsort_t(*t)[size]=a; a=b; b=t;}
	}
	free(b);
}

#define P 1000000007
int a[200000];
int main(void){
	int n=nextint();
	for(int i=0; i<n; i++){
		a[i]=nextint();
	}
	long sum=0, sum2=0;
	for(int i=0; i<n; i++){
		sum=sum+a[i];
		sum2=sum2+(long)a[i]*a[i]%P;
	}
	sum=sum%P;
	sum2=sum2%P;
	int ans = ((long)sum*sum%P+P-sum2)%P;
	ans=ans%2==0?ans/2:(ans+P)/2;
	printf("%d\n", ans);
}
//  [c]
#include <ctype.h>
#include <float.h>
#include <inttypes.h>
#include <limits.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <math.h>
#ifdef __cplusplus
#include <bits/stdc++.h>
#endif
#pragma GCC target("avx2")
#pragma GCC optimize("O3")
//#pragma GCC optimize("unroll-loops")

//char rbuf[]; int rbufl;
//#define getchar() rbuf[rbufl++]
#define getchar getchar_unlocked
#define putchar putchar_unlocked
int32_t nextint(void){ char c=getchar(); while(c!='-'&&(c<'0'||'9'<c)) c=getchar(); bool s=false; if(c=='-'){s=true;c=getchar();} uint32_t x=0; while('0'<=c && c<='9'){ x=x*10+c-'0'; c=getchar(); } return s?-x:x; }
int64_t nextlong(void){ char c=getchar(); while(c!='-'&&(c<'0'||'9'<c)) c=getchar(); int s=0; if(c=='-'){s=1;c=getchar();} uint64_t x=0; while('0'<=c && c<='9'){ x=x*10+c-'0'; c=getchar(); } return s?-x:x; }
uint32_t nextstr(char *s){ char c=getchar(); while(c==' '||c=='\n') c=getchar(); uint32_t len=0; while(c!=' '&&c!='\n'){ *s++=c; len++; c=getchar(); } *s='\0'; return len; }
void printint(int32_t x){ if(x<0){x=-x; putchar('-');}else if(x==0){putchar('0');} int d=0; char s[10]; while(x){ s[d]='0'+x%10; x/=10; d++; } for (int i=d-1; i>=0; i--) putchar(s[i]); putchar('\n'); }
void rsorta_d32(void *base, const int count, const int size, const int index){
	typedef int32_t rsort_t;
	rsort_t (*a)[size] = (rsort_t(*)[size])base;
	rsort_t (*b)[size] = (rsort_t(*)[size])malloc(count*size*sizeof(rsort_t));
	int c[0x100];
	for(int k=0; k<4; k++){
		memset(c, 0, sizeof(c)); for(int i=0; i<count; i++){ c[(a[i][index]>>(k<<3))&0xFF]++; } for(int i=1; i<0x100; i++) c[i]+=c[i-1]; for(int i=count-1; i>=0; i--){ int to=--c[(a[i][index]>>(k<<3))&0xFF]; for(int j=0; j<size; j++){ b[to][j]=a[i][j]; } }{rsort_t(*t)[size]=a; a=b; b=t;}
	}
	free(b);
}

#define P 1000000007
int a[200000];
int main(void){
	int n=nextint();
	for(int i=0; i<n; i++){
		a[i]=nextint();
	}
	int sum=0, sum2=0;
	for(int i=0; i<n; i++){
		sum=(sum+a[i])%P;
		sum2=(sum2+(long)a[i]*a[i]%P)%P;
	}
	int ans = ((long)sum*sum%P+P-sum2)%P;
	ans=ans%2==0?ans/2:(ans+P)/2;
	printf("%d\n", ans);
}
//  [c]
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main(void) {
	int i, j;
	int N;
	//long long int *A;
	int *A;
	long long int ans, temp;
	long long int naive_ans;
	long long int module = 1000000000 + 7;
	char buf[128], *ch;
	char *great_buf;

	fgets(buf, sizeof(buf), stdin);
	ch = strtok(buf, " ");
	N = atoi(ch);

	//A = (long long int *)calloc(N, sizeof(long long int));
	A = (int *)calloc(N, sizeof(int));
	great_buf = (char *)calloc(N*12, sizeof(char));
	fgets(great_buf, N*12, stdin);
	ch = strtok(great_buf, " ");
	A[0] = atoi(ch);
	for(i = 1; i < N; i += 1) {
		ch = strtok(NULL, " ");
		A[i] = atoi(ch);
	}
	free(great_buf);
	/*
	for(i = 0; i < N; i += 1) {
		A[i] = rand()%100000000;
	}
	*/

	/*
	naive_ans = 0;
	for(i = 0; i < N; i += 1) {
		for(j = i + 1; j < N; j += 1) {
			temp = A[i] * A[j];
			temp = temp % module;
			naive_ans += temp;
			naive_ans = naive_ans % module;
		}
	}
	printf("%lld\n", naive_ans);
	*/

	ans = 0;
	temp = 0;
	for(i = 0; i < N; i += 1) {
		temp += A[i];
	}
	for(i = 0; i < N - 1; i += 1) {
		temp -= A[i];
		ans += ((temp % module) * A[i]) % module;
		ans = ans % module;
	}
	printf("%lld\n", ans);

	free(A);
	return 0;
}
//  [c]
#include <stdio.h>
int main(void)
{
    long int N,i,a;
    long int b = 0;
    long int c = 0;
    long int mod = 1000000007;
    scanf("%ld", &N);
    for (i = 1;i <= N;i++)
    {
        scanf("%ld", &a);
        a = a % mod;
        b = b + a;
        b = b % mod;
        c = c + (a * a);
        c = c % mod;
    }
    c = ((b * b) - (2 * c) / 2);
    c = c % mod;
    c = (c / 2);
    c = c % mod;
    printf("%ld", c);
    return 0;
}
//  [c]
#include <stdio.h>
int main(void)
{
    int N,i,a;
    int b = 0;
    int c = 0;
    int mod = 1000000007;
    scanf("%d", &N);
    for (i = 1;i <= N;i++)
    {
        scanf("%d", &a);
        a = a % mod;
        b = b + a;
        b = b % mod;
        c = c + (a * a);
        c = c % mod;
    }
    c = ((b * b) - (2 * c) / 2);
    c = c % mod;
    c = (c / 2);
    c = c % mod;
    printf("%d", c);
    return 0;
}
//  [c]
#include <stdio.h>
int main(void)
{
    int N,i,a;
    int b = 0;
    int c = 0;
    scanf("%d", &N);
    for (i = 1;i <= N;i++)
    {
        scanf("%d", &a);
        b = b + a;
        c = c + (a * a); 
    }
    c = ((b * b) - (2 * c) / 2);
    c = (c / 2);
    printf("%d", c);
    return 0;
}
//  [javascript]
console.log((args=>{
  const [[N],A] = args.trim().split`\n`.map(r=>r.split` `.map(v=>v|0));
  const MOD = 1e9+7;
  const mul = (a,b) => ((a>>16)*b%MOD*65536+(a&65535)*b)%MOD;
  let sum = 0, sub = A.reduce((a,b)=>(a+b)%MOD);
  for ( let i = 0; i < N; i++ ) {
    sub = ( sub + MOD - A[i] ) % MOD;
    sum = (sum + mul(A[i],sub)) % MOD;
  }
  return sum;
})(require('fs').readFileSync('/dev/stdin','utf8')));
//  [javascript]
"use strict";
var input=require("fs").readFileSync("/dev/stdin","utf8");
var cin=input.split(/ |\n/),cid=0;
function next(){return +cin[cid++];}
function nextstr(){return cin[cid++];}
function nextbig(){return BigInt(cin[cid++]);}
function nexts(n,a){return a?cin.slice(cid,cid+=n):cin.slice(cid,cid+=n).map(a=>+a);}
function nextssort(n,a){return a?cin.slice(cid,cid+=n).map(a=>+a).sort((a,b)=>b-a):cin.slice(cid,cid+=n).map(a=>+a).sort((a,b)=>a-b);}
function nextm(h,w,a){var r=[],i=0;if(a)for(;i<h;i++)r.push(cin.slice(cid,cid+=w));else for(;i<h;i++)r.push(cin.slice(cid,cid+=w).map(a=>+a));return r;}
function xArray(v){var a=arguments,l=a.length,r="Array(a["+--l+"]).fill().map(x=>{return "+v+";})";while(--l)r="Array(a["+l+"]).fill().map(x=>"+r+")";return eval(r);}

var mod = 1e9+7;
function mul(){for(var a=arguments,r=a[0],i=a.length;--i;)r=((r>>16)*a[i]%mod*65536+(r&65535)*a[i])%mod;return r;}
var fac=[],finv=[],invs=[],pow2=[];
function fset(n){
  fac.length=n+1,fac[0]=fac[1]=1;
  for(var i=2;i<=n;)fac[i]=mul(fac[i-1],i++);
  finv.length=n+1,finv[0]=finv[1]=1,finv[n]=inv(fac[n]);
  for(i=n;2<i;)finv[i-1]=mul(finv[i],i--);
  //invs.length=n+1,invs[0]=invs[1]=1;
  //for(i=2;i<=n;)invs[i]=mul(fac[i-1],finv[i++]);
  //pow2.length=n+1,pow2[0]=1;
  //for(i=1;i<=n;i++)pow2[i]=pow2[i-1]*2%mod;
}
function inv(b){for(var a=mod,u=0,v=1,t;b;v=t)t=a/b|0,a-=t*b,u-=t*v,t=a,a=b,b=t,t=u,u=v;u%=mod;return u<0?u+mod:u;}
function pow(a,n){for(var r=1;n;a=mul(a,a),n>>=1)if(n&1)r=mul(a,r);return r;}
function ncr(n,r){return mul(fac[n],finv[r],finv[n-r]);}
function npr(n,r){return mul(fac[n],finv[n-r]);}
function mput(n){return (n%mod+mod)%mod;}

var myOut = main();
if(myOut !== undefined)console.log(String(myOut));

function main(){
  var n = next();
  var a = nexts(n);
  var ans = a.reduce((a,b)=>a+b);
  ans %= mod;
  ans = mul(ans,ans);
  for(var i = 0; i < n; i++){
    ans -= mul(a[i],a[i]);
  }
  return mul(mput(ans),inv(2));
}
//  [javascript]
function Main(input) {
	var C = 1e+9 + 7;
	var C2 = 1e+5;	
	input = input.trim().split("\n").map(function(x) { return x.split(" ")});
	let N = parseInt(input[0][0], 10);
	let A = input[1].map(e => parseInt(e, 10));
	let ruisekiwa = [0];
	for (let i = 0; i < N; i++){
		ruisekiwa.push((ruisekiwa[i] + A[i]) % C);
	}
	// console.log(ruisekiwa);

	let ans = 0;
	for (let i = 0; i < (N - 1); i++){
		ans += kakeruR(A[i], mod(ruisekiwa[N] - ruisekiwa[i + 1],C), C, C2);
		ans = mod(ans, C)
	}
	console.log(ans);
}

function mod (i, j){
	return(i % j) < 0 ? (i % j) + 0 + (j < 0 ? -j : j) : (i % j + 0);
}

function kakeruR(a, b, C, C2){
    var tmpQ, tmpR, ans;
    tmpQ = Math.floor(b / C2);  // CAUTION!!
    tmpR = b - (tmpQ * C2);
    ans = (a * tmpQ % C) * C2 % C + (a * tmpR);
    ans %= C;
    return ans;
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
var stdin = require("fs").readFileSync("/dev/stdin", "utf8");

var a =  stdin.split("\n")
var s = a[0]
var w= a[1].split(' ').map( str => parseInt(str, 10));
var mod = 1000000007;
//const w = t.split(' ');
//var all = array.reduce(reducer,0)
let total=0;

//var all = w.reduce((a,x) => a+=x)
let array =[0]

for (let i=0;i+1<=s; i++){
let plus = array[i]+w[i]
array.push(plus)
}
//console.log(array)
var result =0;
var x = array [array.length - 1]
for (let i=0; i<s-1; i++){
  let target = w[i]
  //all = all - w[i]
  var y = array [i+1]
  let sum = target * (x-y)
  total=(total+sum)%mod
  }
console.log(total)
//  [javascript]
var stdin = require("fs").readFileSync("/dev/stdin", "utf8");

var a =  stdin.split("\n")
var s = a[0]
var w= a[1].split(' ').map( str => parseInt(str, 10));
var mod = 1000000007;
//const w = t.split(' ');
//var all = array.reduce(reducer,0)
let total=0;
let ans = 0;
//var all = w.reduce((a,x) => a+=x)
let array =[0]

for (let i=0;i+1<=s; i++){
let plus = array[i]+w[i]
array.push(plus)
}
//console.log(array)
var x = array [array.length - 1]
for (let i=0; i<s-1; i++){
  let target = w[i]
  //all = all - w[i]
  var y = array [i+1]

  let sum = target * (x-y)
  total=total+sum
  ans = total % mod
  }
console.log(ans)
//  [javascript]
var stdin = require("fs").readFileSync("/dev/stdin", "utf8");

var a =  stdin.split("\n")
var s = a[0]
var w= a[1].split(' ').map( str => parseInt(str, 10));
var mod = 1000000007;
//const w = t.split(' ');
//var all = array.reduce(reducer,0)
let total=0;
let ans = 0;
var all = w.reduce((a,x) => a+=x)
for (let i=0; i+1<s; i++){
  let target = w[i]
  all = all - w[i]
  let sum = target * all
  total=total+sum
  ans = total % mod
  }
console.log(ans)
//  [go]
package main

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

const p = 1000000007

func Solve() {
  var N int
  var A []int
  NextInt(&N)
  NextIntSlice(&A)
  B := make([]int, N)
  for i := N - 1; i > 0; i-- {
    B[i - 1] = (B[i] + A[i]) % p
  }
  ans := 0
  for i, a := range A {
    ans = (ans + a * B[i]) % p
  }
  Write(ans)
}

func main() {
  Solve()
  Output()
}

var reader = bufio.NewReaderSize(os.Stdin, 1000000)
var writer = bufio.NewWriter(os.Stdout)
func NextLine() string {
  buffer := make([]byte, 0)
  for true {
    line, isPrefix, err := reader.ReadLine()
    if err != nil { panic(err) }
    buffer = append(buffer, line...)
    if !isPrefix { break }
  }
  return string(buffer)
}
func NextInt(A ...*int) {
  L := strings.Split(NextLine(), " ")
  for i, a := range A {
    *a, _ = strconv.Atoi(L[i])
  }
}
func NextIntSlice(A *[]int) {
  L := strings.Split(NextLine(), " ")
  if len(L) == 1 && L[0] == "" {
    (*A) = make([]int, 0)
    return
  }
  (*A) = make([]int, len(L))
  for i, l := range L {
    (*A)[i], _ = strconv.Atoi(l)
  }
}
func NextFloat(A ...*float64) {
  L := strings.Split(NextLine(), " ")
  for i, a := range A {
    *a, _ = strconv.ParseFloat(L[i], 64)
  }
}
func NextFloatSlice(A *[]float64) {
  L := strings.Split(NextLine(), " ")
  if len(L) == 1 && L[0] == "" {
    (*A) = make([]float64, 0)
    return
  }
  (*A) = make([]float64, len(L))
  for i, l := range L {
    (*A)[i], _ = strconv.ParseFloat(l, 64)
  }
}
func Write(S ...interface{}) {
  fmt.Fprintln(writer, S...)
}
func WriteIntSlice(A []int) {
  B := make([]interface{}, len(A))
  for i, a := range A { B[i] = a }
  fmt.Fprintln(writer, B...)
}
func Output() {
  _ = writer.Flush()
}
func MaxInt(A ...int) int {
  max := A[0]
  for _, a := range A {
    if max < a { max = a }
  }
  return max
}
func MinInt(A ...int) int {
  min := A[0]
  for _, a := range A {
    if a < min { min = a }
  }
  return min
}
func SumInt(A ...int) int {
  sum := 0
  for _, a := range A {
    sum += a
  }
  return sum
}
func AbsInt(x int) int {
  if x < 0 { x = -x }
  return x
}
//  [go]
package main

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

func main() {
	sc := NewScanner()

	const N = 1_000_000_007

	n := sc.ReadInt()
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = sc.ReadInt()
	}

	sum := 0
	sqSum := 0
	for _, ai := range a {
		sum += ai
		sum %= N

		sqSum += ai * ai % N
		sqSum %= N
	}
	sumSq := sum * sum % N
	df := ((sumSq - sqSum) + N) % N
	if df%2 == 0 {
		fmt.Println(df / 2)
	} else {
		fmt.Println((df + N) / 2)
	}
}

// from [my library](https://github.com/ikngtty/go-contestlib)
// -   math/simple

func Abs(x int) int {
	if x >= 0 {
		return x
	}
	return -x
}

func Min(values ...int) int {
	if len(values) == 0 {
		panic("no values")
	}

	min := values[0]
	for _, v := range values {
		if v < min {
			min = v
		}
	}
	return min
}

func Max(values ...int) int {
	if len(values) == 0 {
		panic("no values")
	}

	max := values[0]
	for _, v := range values {
		if v > max {
			max = v
		}
	}
	return max
}

func Pow(base, exponent int) int {
	if exponent < 0 {
		panic(fmt.Sprintf("exponent (%d) should not be a minus", exponent))
	}

	answer := 1
	for i := 0; i < exponent; i++ {
		answer *= base
	}
	return answer
}

func Ceil(divident, dividor int) int {
	if dividor == 0 {
		panic("dividor should not be 0")
	}

	quo := divident / dividor
	rem := divident % dividor

	if rem != 0 {
		if (divident > 0 && dividor > 0) ||
			(divident < 0 && dividor < 0) {
			return quo + 1
		}
	}
	return quo
}

// -   sortutil

func ReverseInts(a []int) {
	sort.Sort(sort.Reverse(sort.IntSlice(a)))
}

func ReverseStrings(a []string) {
	sort.Sort(sort.Reverse(sort.StringSlice(a)))
}

// -   io

type Scanner struct {
	bufScanner *bufio.Scanner
}

func NewScanner() *Scanner {
	bufSc := bufio.NewScanner(os.Stdin)
	bufSc.Split(bufio.ScanWords)
	bufSc.Buffer(nil, 100000000)
	return &Scanner{bufSc}
}

func (sc *Scanner) ReadString() string {
	bufSc := sc.bufScanner
	bufSc.Scan()
	return bufSc.Text()
}

func (sc *Scanner) ReadInt() int {
	bufSc := sc.bufScanner
	bufSc.Scan()
	text := bufSc.Text()

	num, err := strconv.Atoi(text)
	if err != nil {
		panic(err)
	}
	return num
}

func (sc *Scanner) ReadFloat() float64 {
	bufSc := sc.bufScanner
	bufSc.Scan()
	text := bufSc.Text()

	num, err := strconv.ParseFloat(text, 64)
	if err != nil {
		panic(err)
	}
	return num
}
//  [go]
package main

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

var sc *bufio.Scanner

const bufferSize = 1024

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

var production bool

func debugf(format string, v ...interface{}) {
	if !production {
		fmt.Printf(format, v...)
	}
}

func answer(reader io.Reader, writer io.Writer) {
	sc = bufio.NewScanner(reader)
	buf := make([]byte, bufferSize)
	sc.Buffer(buf, 1e+7)
	sc.Split(bufio.ScanWords)
	n := nextInt()
	a := make([]int, n)

	for i := range a {
		a[i] = nextInt()
	}

	mod := int(1e9) + 7

	sum := a[0]
	ans := 0
	for i := 1; i < n; i++ {
		ans += sum * a[i]
		ans %= mod
		sum += a[i]
	}

	_, _ = fmt.Fprintf(writer, "%d", ans)
}

func main() {
	production = true
	answer(os.Stdin, os.Stdout)
}
//  [ruby]
mod = 1_000_000_007

n = gets.to_i
a = gets.split.map &:to_i

tmp0 = a.sum
tmp0 = ((tmp0 % mod) ** 2) % mod
tmp1 = a.sum { |e| e ** 2 } % mod
ans = tmp0 < tmp1 ? tmp0 - tmp1 + mod : tmp0 - tmp1

if ans.odd?
  puts (ans + mod) / 2
else
  puts ans / 2
end
//  [ruby]
mod = 1_000_000_007

gets
a = gets.split.map &:to_i

tmp0 = a.sum ** 2
tmp1 = a.sum { |e| e ** 2 }
puts (tmp0 - tmp1) / 2 % mod

# tmp0 = a.sum
# tmp0 = ((tmp0 % mod) ** 2) % mod

# tmp1 = a.sum { |e| e ** 2 }

# tmp1 %= mod

# ans = tmp0 < tmp1 ? tmp0 - tmp1 + mod : tmp0 - tmp1

# if ans.odd?
#   puts (ans + mod) / 2
# else
#   puts ans / 2
# end
//  [ruby]
END { load __FILE__ unless $stdin.eof? }

@m = 10**9 + 7

n = gets.to_i
a = gets.split.map!(&:to_i)

a1sum = a.sum % @m
a2sum = a.inject(0) { |s, ai| (s + ai * ai) % @m }

a_sum = (a1sum * a1sum - a2sum) % @m
a_sum += @m if a_sum.odd?

puts a_sum / 2
//  [ruby]
n = gets.chomp.to_i
arr = gets.chomp.split(' ').map(&:to_i)
mod = 1000000007

i = 0
sum = 0
each_sum = 0
while i < n-1
  each_sum += arr[i]
  sum += arr[i] * (arr.sum - each_sum)
  # a*b+ a*c + a*d + b*c + b*d + c*d  
  # a(b+c+d) + b(c+d) + 
  # 
  #
  i += 1
end
puts sum%mod
//  [ruby]
N = gets.chomp.to_i
A = gets.split(' ').map(&:to_i)

MOD = 10 ** 9 + 7

sum = 0

(1..(N - 1)).each do |i|
    sum += (A[i] * (A[0..(i - 1)].sum % MOD)) % MOD
end

puts sum % MOD
//  [ruby]
N = gets.chomp.to_i
A = gets.split(' ').map(&:to_i)

MOD = 10 ** 9 + 7

sum = 0

(0..(N - 2)).each do |i|
    ((i + 1)..(N - 1)).each do |j|
        sum += (A[i] * A[j]) % MOD 
        sum %= MOD
    end
end

puts sum
//  [rust]
// -*- coding:utf-8-unix -*-

use proconio::input;

fn main() {
    input! {
        n: usize,
        a: [u64; n],
    }

    let mut ans = 0;
    let mut part_sum = a.iter().sum::<u64>();
    let divisor = 10_u64.pow(9) + 7;
    // println!("ps: {}", part_sum);
    // println!("{:?}", a);
    for i in 1..n {
        // println!("ai-1: {}", a[i - 1]);
        part_sum = (part_sum + divisor - a[i - 1]) % divisor;
        // println!("ps: {}", part_sum);
        ans = (ans + (a[i - 1] * part_sum) % divisor) % divisor;
    }
    println!("{}", ans);
}
//  [rust]
use std::mem;
use std::io;

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

fn mod_add(a:&u64, b:&u64, m:&u64) -> u64 {
    (*a%*m + *b%*m)%*m
}

fn mod_sub(a:&u64, b:&u64, m:&u64) -> u64 {
    let mut ret = (*a%*m) as i64 - (*b%*m) as i64;
    if ret < 0 {
        ret += *m as i64;
    }
    ret as u64
}

fn mod_mul(a:&u64, b:&u64, m:&u64) -> u64 {
    ((*a%*m)*(*b%*m))%m
}

fn mod_pow(a:&u64, b:&u64, m:&u64) -> u64 {
    let mut ret:u64 = 1;
    let mut aa = *a%*m;
    let mut bb = *b;
    while bb != 0 {
        if bb&(1_u64) == 1 {
            ret = (ret*aa)%*m;
        }
        aa = (aa*aa)%*m;
        bb >>= 1;
    }
    ret
}

fn mod_inv(a:&u64, p:&u64) -> u64 {
    // aのmod p における逆元を求める
    let mut aa = *a;
    let mut b = *p;
    let mut u:i64 = 1;
    let mut v:i64 = 0;
    while b != 0 {
        let t = aa/b;
        aa = aa - t*b;
        mem::swap(&mut aa, &mut b);
        u = u - (t as i64) * v;
        mem::swap(&mut u, &mut v);
    }
    u = u % (*p as i64);
    if u < 0 {
        u += (*p as i64);
    }
    u as u64
}

fn mod_div(a:&u64, b:&u64, m:&u64) -> u64 {
    let mut ret = *a%*m;
    let inv = *b%*m;
    ret = (ret * mod_inv(&inv, m))%*m;
    ret
}

fn COMinit(fac:&mut Vec<u64>, finv:&mut Vec<u64>, inv:&mut Vec<u64>, memMax:u64, m:&u64){
    fac.push(1); fac.push(1); 
    finv.push(1); finv.push(1); 
    for i in 2..memMax as usize {
        fac.push((fac[i-1]*(i as u64))%*m);
        inv.push(*m - ((inv[(*m as usize)%i] * (*m/(i as u64)) )%*m) );
        finv.push( (finv[i-1]*(inv[i]) ) % *m );
    }
}

fn comb(n:&u64, k:&u64, m:&u64, fac:&Vec<u64>, finv:&Vec<u64>) -> u64 {
    if *n < *k {
        return 0
    }
    fac[*n as usize] * ((finv[*k as usize]*finv[(*n - *k) as usize] )%*m) % *m
}

fn main() {
    let n:u64 = procon_read()[0];
    let v:Vec<u64> = procon_read();
    let m:u64 = 1000000007;// 10⁹ +7
    let mut ret = 0_u64;
    for j in 1..n as usize {
        for i in 0..j as usize {
            ret = mod_add(&ret, &mod_mul(&v[i], &v[j], &m), &m);
        }
    }
    println!("{}", ret);
}
//  [rust]
fn read<T: std::str::FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().parse().ok().unwrap()
}

fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    read::<String>()
.split_whitespace()
        .map(|e| e.parse().ok().unwrap())
        .collect()
}

fn read_vec2<T: std::str::FromStr>(n: u32) -> Vec<Vec<T>> {
    (0..n).map(|_| read_vec()).collect()
}

fn main() {
    // solver code...
    let _ = read::<i64>();
    let mut a_vec = read_vec::<i64>();
    a_vec = a_vec.sort();
    let MOD = 1000000007;
    let mut sum = 0;
    for a in &a_vec {
        sum += a;
    }

    let mut ans = 0;
    for a in &a_vec {
        sum -= a;
        ans += (a * sum)%MOD;
        ans %= MOD;
    }

    println!("{}", ans);
}
//  [rust]
fn read<T: std::str::FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().parse().ok().unwrap()
}

fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    read::<String>()
.split_whitespace()
        .map(|e| e.parse().ok().unwrap())
        .collect()
}

fn read_vec2<T: std::str::FromStr>(n: u32) -> Vec<Vec<T>> {
    (0..n).map(|_| read_vec()).collect()
}

fn main() {
    // solver code...
    let _ = read::<i64>();
    let mut a_vec = read_vec::<i64>();
    a_vec.sort();
    let mut max_a: i64 = 0;
    let MOD = 1000000007;
    let mut sum = 0;
    for a in &a_vec {
        sum += a;
    }

    let mut ans = 0;
    for a in &a_vec {
        sum -= a;
        ans += (a * sum)%MOD;
        ans %= MOD;
    }

    println!("{}", ans);
}
//  [swift]
func main(input1: String = readLine()!, input2: String = readLine()!) {
    let integers = input2.split(separator: " ").map { Int($0)! }
    
    let mod = 1000000007
    var summary = 0
    for i in integers {
        summary += i
        summary %= mod
    }
    var result = 0
    for i in integers {
        summary -= i
        if summary < 0 {
            summary += mod
        }
        result += i * summary
        result %= mod
    }
    print(result)
}

main()
//  [swift]
let N = Int(readLine()!)!
let AN = readLine()!.split(separator: " ").compactMap { Int($0) }
let mod = 1000000007

var sumAN = AN.reduce(0) { ($0 + $1) % mod }
var sumList: [Int] = []
for i in 0..<N {
    sumAN -= AN[i]
    sumList.append(sumAN)
}

var result = 0
for i in 0..<N {
    result += AN[i] * sumList[i]
    result %= mod
}
print(result)
//  [swift]
let N = Int(readLine()!)!
let AN = readLine()!.split(separator: " ").compactMap { Int($0) }
let mod = 1000000007

var sumAN = AN.reduce(0) { $0 + $1 }
var sumList: [Int] = []
for i in 0..<N {
    sumAN -= AN[i]
    sumList.append(sumAN)
}

var result = 0
for i in 0..<N {
    result += AN[i] * sumList[i]
    result %= mod
}
print(result)
//  [swift]
import Foundation

let N = Int(readLine()!)!
let AN = readLine()!.split(separator: " ").compactMap { Int($0) }

var sumAN = AN.reduce(0) { $0 + $1 }
var sumList: [Int] = []
for i in 0..<N {
    sumAN -= AN[i]
    sumList.append(sumAN)
}

var result = 0
for i in 0..<N-1 {
    result += AN[i] * sumList[i]
    result %= Int(pow(10.0, 9)) + 7
}
print(result)
//  [typescript]
import * as fs from 'fs';

const M = 10 ** 9 + 7;
const Mb = BigInt(M);

function modX(num: number) {
  return num % M;
}

function modX2(num1: number, num2: number) {
  return Number((BigInt(num1) * BigInt(num2)) % Mb);
}

function main(input) {
  input = input.split("\n");
  const N = parseInt(input[0]);
  const AList = input[1].split(' ').map(i => parseInt(i));
  let ans = 0;
  let sum = 0;
  for (let i = 1; i < N; i++) {
    sum += AList[i - 1];
    sum = modX(sum);
    ans += modX2(AList[i], sum);
    ans = modX(ans);
  }
  console.log('%s', ans);
}

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

// メイン
function main(input: string[]) {
    const n: number = +input[0];
    const a: bigint[] = input[1].split(" ").map(x => BigInt(x));
    const m:bigint = BigInt(Math.pow(10, 9) + 7);
    var p:bigint = BigInt(0);
    var s:bigint = BigInt(0);
    for (var i = 0; i < a.length; i++) {
        console.debug("i=", i, "p=", p, "s=", s);
        p = (p + a[i] * s) % m;
        s = (s + a[i]) % m;
    }
    var x = Number(p);
    console.log(x);
}

// エントリポイント
// - OSによるパラメタの処理の違いを吸収
function entrypoint() {
    try {
        var input = fs.readFileSync("/dev/stdin", "utf8").split("\n");
        console.debug = function () { };
        main(input);
    }
    catch (ex) {
        console.log("----");
        console.log("file='%s'", __filename.split("\\").slice(-1)[0]);
        console.log("----");
        const lines: string[] = [];
        // @ts-ignore
        const reader = require('readline').createInterface({
            // @ts-ignore
            input: process.stdin,
            // @ts-ignore
            output: process.stdout
        });
        reader.on('line', function (line: string) {
            lines.push(line);
        });
        reader.on('close', function () {
            input = lines;
            console.log("input=%o", input);
            console.time();
            console.log("----")
            main(input);
            console.log("----")
            console.timeEnd();
        });
    }
}
entrypoint();
//  [typescript]
import * as fs from 'fs';

const input = fs.readFileSync('/dev/stdin', 'utf8');
// const input = fs.readFileSync('./input.txt', 'utf8');
const L = BigInt(10 ** 9 + 7);

_c(input);

function _c(input: string) {
  const [_N, _A] = input.split('\n');
  const A = _A.split(' ').map((s) => BigInt(s));
  // console.log(A);

  const sumFor: bigint[] = [];
  sumFor[A.length - 1] = A[A.length - 1];
  for (let i = A.length - 2; i > 0; i--) {
    sumFor[i] = A[i] + sumFor[i + 1];
  }
  // console.log(sumFor);

  let sum = 0n;
  for (let i = 0; i < A.length - 1; i++) {
    sum = (sum + A[i] * sumFor[i + 1]) % L;
  }

  console.log(sum.toString());
}
//  [typescript]
var main = (input: string) => {
    let t: string[] = input.split("\n");
    const n: number = parseInt(t[0]);
    const a: number[] = t[1].split(" ").map(e => parseInt(e, 10));

    const mod: number = 1_000_000_007;
    let count: number = 0;
    for (let i: number = 0; i < n - 1; i++) {
        let sum = 0;
        for (let j: number = i + 1; j < n; j++) {
            sum += a[j];
        }
        count = (count + a[i] * sum) % mod;
    }
    console.log(count);
}

main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [typescript]
var main = (input: string) => {
    let t: string[] = input.split("\n");
    const n: number = parseInt(t[0]);
    const a: number[] = t[1].split(" ").map(e => parseInt(e, 10));

    const mod: number = 1_000_000_007;
    let count: number = 0;
    for (let i: number = 0; i < n - 1; i++) {
        for (let j: number = i + 1; j < n; j++) {
            count = (count + a[i] * a[j]) % mod;
        }
    }
    console.log(count);
}

main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [typescript]
// @ts-ignore
import * as fs from 'fs';

// メイン
function main(input: string[]) {
    const n: number = +input[0];
    const a: number[] = input[1].split(" ").map(x => +x);
    const m = Math.pow(10, 9) + 7;
    var p = 0;
    var s = 0;
    for (var i = 0; i < a.length; i++) {
        console.debug("i=", i, "p=", p, "s=", s);
        p = (p + a[i] * s) % m;
        s = (s + a[i]) % m;
    }
    console.log(p);
}

// エントリポイント
// - OSによるパラメタの処理の違いを吸収
function entrypoint() {
    try {
        var input = fs.readFileSync("/dev/stdin", "utf8").split("\n");
        console.debug = function () { };
        main(input);
    }
    catch (ex) {
        console.log("----");
        console.log("file='%s'", __filename.split("\\").slice(-1)[0]);
        console.log("----");
        const lines: string[] = [];
        // @ts-ignore
        const reader = require('readline').createInterface({
            // @ts-ignore
            input: process.stdin,
            // @ts-ignore
            output: process.stdout
        });
        reader.on('line', function (line: string) {
            lines.push(line);
        });
        reader.on('close', function () {
            input = lines;
            console.log("input=%o", input);
            console.time();
            console.log("----")
            main(input);
            console.log("----")
            console.timeEnd();
        });
    }
}
entrypoint();
//  [python]
a,b,c,d = map(int, input().split())
Al = list(range(a,b))
Bo = list(range(c,d))
print(len(set(Al) & set(Bo)))
//  [python]
a, b, c, d = map(int, input().split())
print(max(0, min(b, d) - max(a, c) ))
//  [python]
a,b,c,d = map(int,input().split())
if a <= c <= b <= d:
    print(b - c)
elif c <= a <= d <= b:
    print(d - a)
elif a <= c <= d <= b:
    print(d - c)
elif c <= a <= b <= d:
    print(b - a)
else:
#elif b <= c or d <= a:
    print(0)
//  [python]
A, B, C, D = map(int, input().split())

M1 = max(A, C)
M2 = min(B, D)

if B >= C:
    print(M2 - M1)

else:
    print(0)
//  [python]
A, B, C, D = map(int, input().split())

M1 = max(A, C)
M2 = min(B, D)

if B > C:
    print(abs(M1 - M2))

else:
    print(0)
//  [python]
A, B, C, D = map(int, input().split())

if A<=C and D<=B: print(D-C)

if C<=A and B<=D: print(B-A)


if (A<=C and C<= B and B<=D): print(B-C)

if C<=A and A<=D and D<=B: print(D-A)

if B<=C or D<=A: print(0)
//  [java]
import java.io.*;
import java.util.*;
import static java.lang.Math.*;

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

    public void solve(String[] args) {
        MyScanner scanner = new MyScanner();
        int A = scanner.nextInt();
        int B = scanner.nextInt();
        int C = scanner.nextInt();
        int D = scanner.nextInt();
        boolean a = false;
        boolean b = false;
        int ans = 0;
        for (int i = 0; i <= 100; i++) {
            if (i == A) {
                a = true;
            }
            if (i == B) {
                a = false;
            }
            if (i == C) {
                b = true;
            }
            if (i == D) {
                b = false;
            }
            if (a && b) {
                ans++;
            }
        }
        System.out.println(ans);
    }

    private class MyScanner {
        String[] s;
        int i;
        BufferedReader br;
        String reg = " ";

        MyScanner () {
            s = new String[0];
            i = 0;
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        public String next() {
            try {
                if (i < s.length) return s[i++];
                String line = br.readLine();
                while (line.equals("")) {
                    line = br.readLine();
                }
                s = line.split(reg, 0);
                i = 0;
                return s[i++];
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        public int nextInt() {
            try {
                return Integer.parseInt(next());
            } catch (Exception e) {
                e.printStackTrace();
            }
            return -1;
        }

        public double nextDouble() {
            try {
                return Double.parseDouble(next());
            } catch (Exception e) {
                e.printStackTrace();
            }
            return -1;
        }

        public long nextLong()  {
            try {
                return Long.parseLong(next());
            } catch (Exception e) {
                e.printStackTrace();
            }
            return -1;
        }
    }
}
//  [java]
import java.io.*;
import java.util.*;
import java.math.*;
import java.util.concurrent.*;

class Main
{
    static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
	static FastScanner sc=new FastScanner(br);
    static PrintWriter out=new PrintWriter(System.out);
	static Random rnd=new Random();
	
    public static void main(String args[]) throws Exception
    {
		int[] cnt=new int[105];
		
		int l1=sc.nextInt(),r1=sc.nextInt();
		
		for(int i=l1+1;i<=r1;i++)
		{
			cnt[i]++;
		}
		
		int l2=sc.nextInt(),r2=sc.nextInt(),res=0;
		
		for(int i=l2+1;i<=r2;i++)
		{
			if(cnt[i]>0)
			{
				res++;
			}
		}
		
		out.println(res);out.close();
    }
}
class FastScanner
{
    BufferedReader in;
    StringTokenizer st;

    public FastScanner(BufferedReader in) {
        this.in = in;
    }
	
    public String nextToken() throws Exception {
        while (st == null || !st.hasMoreTokens()) {
            st = new StringTokenizer(in.readLine());
        }
        return st.nextToken();
    }
	
	public String next() throws Exception {
		return nextToken().toString();
	}
	
    public int nextInt() throws Exception {
        return Integer.parseInt(nextToken());
    }

    public long nextLong() throws Exception {
        return Long.parseLong(nextToken());
    }

    public double nextDouble() throws Exception {
        return Double.parseDouble(nextToken());
    }
}
//  [java]
package practice;


import java.util.*;

public class AC70B {
	public static void main (String[] args)
	{
		Scanner in = new Scanner (System.in);
		int[] A= new int[2];
		int[] B  = new int[2];
		int max_low=0;
		int min_high=0;
		
		for(int i=0; i<2; i++)
		{
			A[i]=in.nextInt();
		}
		for(int i=0; i<2; i++)
		{
			B[i]=in.nextInt();
		}
		
		max_low=Math.max(A[0],B[0]);
		min_high= Math.min(A[1],B[1]);
		
		if (max_low>min_high)
			System.out.println("0");
		
		else
			System.out.println(min_high-max_low);
		
		
	}
}
//  [java]
import java.util.*;

public class AC70B {
	public static void main (String[] args)
	{
		Scanner in = new Scanner (System.in);
		int[] A= new int[2];
		int[] B  = new int[2];
		int max_low=0;
		int min_high=0;
		
		for(int i=0; i<2; i++)
		{
			A[i]=in.nextInt();
		}
		for(int i=0; i<2; i++)
		{
			B[i]=in.nextInt();
		}
		
		max_low=Math.max(A[0],B[0]);
		min_high= Math.min(A[1],B[1]);
		
		if (max_low>min_high)
			System.out.println("0");
		
		else
			System.out.println(min_high-max_low);
		
		
	}
}
//  [cpp]
#include <cstdio>

int main() {
  int a, b, c, d;
  scanf("%d%d%d%d", &a, &b, &c, &d);
  if(c > a)
    a = c;
  if(d < b)
    b = d;
  if(a < b)
    printf("%d", b - a);
  else
    printf("0");
  return 0;
}
//  [cpp]
#include <cstdio>
#include <algorithm>

using namespace std;

inline int read()
{
	int x=0,f=1; char ch=getchar();
	while(ch<'0' || ch>'9') {if(ch=='-') f=-1;ch=getchar();}
	while(ch>='0' && ch<='9') x=x*10+ch-'0',ch=getchar();
	return x*f;
}

int main()
{
	int a,b,c,d;
	a=read(); b=read(); c=read(); d=read();
	a=max(a,c); b=min(b,d);
	printf("%d\n",max(0,b-a));
	return 0;
}
//  [cpp]
#include <cstdio>
#include <algorithm>
int main() {
    int a, b, c, d;
    scanf("%d %d %d %d", &a, &b, &c, &d);
    if(a > c) std::swap(a,c), std::swap(b, d);
    int len;
    if(d > b) len = (b - c > 0) ? (b-c) : 0;
    else len = d - c;
    printf("%d", len);
    return 0;
}
//  [cpp]
#include<bits/stdc++.h>
using namespace std;

int main(){
  int a,b,c,d,time;
  cin >>a>>b>>c>>d;
  if(a>=d||b<=c){
    time=0;
  }else if(a<=b){
    time=(int)min(c-b,d-b);
  }else{
    time=(int)min(c-a,d-a);
  }
  cout << time << endl;
}
//  [cpp]
#include<bits/stdc++.h>
using namespace std;

int main(){
  int a,b,c,d,time;
  cin >>a>>b>>c>>d;
  if(a>=d||b<=c){time=0;
  }else if(a<=b){
    time=min(c-b,d-b);
  }else{
    time=min(c-a,d-a);
  }
  cout << time << endl;
}
//  [cpp]
#include<bits/stdc++.h>
using namespace std;

int main(){
  int a,b,c,d,time;
  cin >>a>>b>>c>>d;
  if(a>=d||b<=c){time=0;}
  else if(a<=b){
    time=min(c-b,d-b);
  }else{
    time=min(c-a,c-b);
  }
  cout << time << endl;
}
//  [c]
#include <stdio.h>


int main(void){
    int A,B,C,D;
    scanf("%d %d %d %d",&A,&B,&C,&D);
    if(A<=D&&C<=B){
        int po1;
        if(A>C)po1=A;
        else po1=C;
        int po2;
        if(B<D)po2=B;
        else po2=D;
        printf("%d",po2-po1);
    }
    else printf("0");
    return 0;
}
//  [c]
#include<stdio.h>
int main(){
    int a,b,c,d;
    int s[100];
    int t[100];
    int count=0;
    scanf("%d %d %d %d",&a,&b,&c,&d);
    for(int i=0;i<100;i++){
        if((a<=i)&&(i<b)){
            s[i]=1;
        }else{
            s[i]=0;
        }
    }
    for(int i=0;i<100;i++){
        if((c<=i)&&(i<d)){
            t[i]=1;
        }else{
            t[i]=0;
        }
    }
    for(int i=0;i<100;i++){
            if((s[i]==1)&&(t[i]==1)){
                count=count+1;
            }else{

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

int main()
{
int a, b, c, d;
int t;

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

if(b <= c || d <=a ){
  t = 0;
}
else {
  if(a <=c){
    if(b <=d){
      t = b - c;
    }
    else{
      t = d-c;
    }
  }
  else{
    if(b <=d){
      t = b - a;
    }
    else{
      t = d-a;
    }
  }
}


  printf("%d\n", t);

return 0;
}
//  [c]
#include <stdio.h>
#include <string.h>
#pragma warning(disable : 4996)

int main()
{
    int A, B, C, D;
    int i;
    int a[100] = {0};
    int b[100] = {0};
    int c[100] = { 0 };
    int time = 0;

    scanf("%d %d %d %d", &A, &B, &C, &D);

    for (i = A; i <= B; i++) {
        a[i] = 1;
    }

    for (i = C; i <= D; i++) {
        b[i] = 1;
    }

    for (i = 0; i < 100; i++) {
        c[i] = a[i] + b[i];
        if (c[i] == 2)
            time++;
    }

 
    if (time == 0)
        printf("%d", time);
    else
    printf("%d", time-1);

    return 0;
}
//  [c]
#include<stdio.h>

int min(int a,int b)
{

   if(a>b)return b;
   else return a;
}
int max(int a, int b)
{
    if(a>b)return a;
    else return b;
}

int main()
{
    int a,b,c,d,e,f;
    int ans=0;

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

    if(b<c)
    {
        ans=0;
    }
    else if(b>=c)
    {
       e=min(b,d);
       f=max(a,c);
       ans=e-f;
    }
    printf("%d\n",ans);

    return 0;
}
//  [c]
#include<stdio.h>

int min(int a,int b)
{

   if(a>b)return b;
   else return a;
}
int max(int a, int b)
{
    if(a>b)return a;
    else return b;
}

int main()
{
    int a,b,c,d,e,f;
    int ans=0;

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

    if(b<=c)
    {
        ans=0;
    }
    else if(b>c)
    {
       e=min(b,d);
       f=max(a,c);
       ans=e-f;
    }
    printf("%d\n",ans);

    return 0;
}
//  [javascript]
function Main(inp) {
    var input = inp.split('\n')[0].split(' ').map(function(n) {
        return Number(n);
    });
    var count = 0;
    for(var i = 0; i <= 100; i++) {
        var onA = false, onB = false;
        if (input[0] <= i && i < input[1]) {
            onA = true;
        }
        if (input[2] <= i && i < input[3]) {
            onB = true;
        }
        if (onA && onB) {
            count += 1;
        }
    }
    console.log(count);
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
function Main(input) {
	var input = input.split(" ");
  	input = input.map(function (element) { return Number(element); });
  	var n=0;
	for(i=input[0];i<=input[1];i++){
      if(i>=input[2]&&i<=input[3]){        
        n++;
      }
    }
	if(n!==0){
	  n--;
  	}
      console.log(n);
}
 
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
function Main(input){
    input = input.split(" ");

    input[0] = parseInt(input[0], 10);
    input[1] = parseInt(input[1], 10);
    input[2] = parseInt(input[2], 10);
    input[3] = parseInt(input[3], 10);

    if(input[2] >= input[1]){
        console.log(0);
    }else if(input[3] <= input[0]){
        console.log(0);
    }else{
        if(input[0] < input[2]){
            var start = input[2]
        }else{
            var start = input[0]
        }

        if(input[1] < input[3]){
            var end = input[1]
        }else{
            var end = input[3]
        }

        console.log('%d', end - start);
    }
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
'use strict';
function Main(stdin){
  const [A, B, C, D] = stdin.trim().split(' ').map(str => Number(str));
  
  let start =  A < C ? C : A;
  let end = B < D ? B : D;
  let result = end < start ? 0 : end - start;
  console.log(result);
}

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

function main(input) {
  const inputList = input.split(' ');
  const [a, b, c, d] = inputList.map(input => Number(input))

  const left = Math.max(a, c)
  const right = Math.min(b, d)

  if (left > right) {
    console.log(String(0))
  } else {
    console.log(String(right-left))
  }
}

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

function main(input) {
  const inputList = input.split(' ');
  const [a, b, c, d] = inputList.map(input => Number(input))

  const left = Math.max(a, c)
  const right = Math.min(b, d)

  if (left > right) {
    console.log(0)
  } else {
    console.log(right-left)
  }
}

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

import (
  "fmt"
)

func maxInt(a ...int) int {m := a[0]; for _, x := range a {if x > m {m = x}}; return m}
func minInt(a ...int) int {m := a[0]; for _, x := range a {if x < m {m = x}}; return m}

func main() {
  var a, b, c, d int 
  fmt.Scan(&a, &b, &c, &d)
  res := maxInt(0, minInt(b, d) - maxInt(a, c))
  fmt.Println(res)
}
//  [go]
package main

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

var sc = bufio.NewScanner((os.Stdin))

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

func nextInt() int {
	l := nextLine()
	i, e := strconv.Atoi(l)
	if e != nil {
		panic(e)
	}
	return i
}

func main() {
	sc.Split(bufio.ScanWords)
	A, B, C, D := nextInt(), nextInt(), nextInt(), nextInt()

	fmt.Printf("%d\n", ABC070B(A, B, C, D))
}

// ABC070B ...
func ABC070B(A, B, C, D int) int {
	if B < C || D < A {
		return 0
	}

	if A < C && D < B {
		return D - C
	}
	if C < A && B < D {
		return B - A
	}

	if A < C {
		return B - C
	}

	return D - A
}
//  [ruby]
A, B, C, D = gets.split.map &:to_i
ret = 0
if B < C || D < A
    ret = 0
elsif C <= A && B <= D
    ret = B - A
elsif C <= A && D <= B
    ret = D - A
elsif A <= C && D <= B
    ret = D - C
elsif A <= C && B <= D
    ret = B - C
end
puts ret
//  [ruby]
a, b, c, d = gets.chomp.split.map(&:to_i)

ans = [b, d].min - [a, c].max

if 0 < ans
  puts ans
else
  puts "0"
end
//  [ruby]
input = gets.chomp.split
a = input[0].to_i
b = input[1].to_i
c = input[2].to_i
d = input[3].to_i

start = a > c ? a : c
finish = b < d ? b : d
seconds = finish - start

puts seconds > 0 ? seconds : 0
//  [ruby]
a,b,c,d=gets.split.map(&:to_i)
p ([*a..b]&[*c..d]).size-1
//  [ruby]
a,b,c,d=gets.split.map(&:to_i)
p ([*a..b]&[*c..d]).size
//  [ruby]
a,b,c,d = gets.chomp.split(" ").map(&:to_i)
arr = Array.new(101,0)
(a..b).each do |i|
  arr[i] += 1
end
(c..d).each do |i|
  arr[i] += 1
end
count = 0
st = []
arr.each_with_index do |o,j|
  if o == 2
    st << j
  end
end
if st != []
    puts st.pop - st.shift
else
    puts "0"
end
//  [rust]
use std::io;
use std::cmp::{min, max};

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

fn main() {
	let v:Vec<i32> = procon_read();
	let a = v[0];
	let b = v[1];
	let c = v[2];
	let d = v[3];
	let mut pusht = 0;
	if !(c > b || d < a) {
		pusht = min(d, b) - max(a, c);
	}
	println!("{}", pusht);
}
//  [rust]
use std::io::*;
use std::str::FromStr;

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

use std::cmp::max;
use std::cmp::min;

fn main() {
    let a: i64 = read();
    let b: i64 = read();
    let c: i64 = read();
    let d: i64 = read();
    if a > c {
        println!("{}", max(min(d - a, b - a), 0));
        return;
    }
    if c > a {
        println!("{}", max(min(b - c, d - c), 0));
        return;
    }
    println!("{}", min(b, d) - a);
}
//  [rust]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let mut s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

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

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

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

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

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

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

    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}
fn main() {
    input!{
        u: [i32; 4],
    };
    println!(
        "{}",
        (0..100)
        .filter(|&x| x >= u[0] && x < u[1] && x >= u[2] && x < u[3])
        .count()
    );
}
//  [rust]
use std::io;
use std::cmp::{min, max};

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

fn main() {
	let v:Vec<i32> = procon_read();
	let a = v[0];
	let b = v[1];
	let c = v[2];
	let d = v[3];
	let mut pusht = 0;
	if (c >= a && c <= b) || (d >= a && d <= b) {
		pusht = min(d, b) - max(a, c);
	}
	println!("{}", pusht);
}