message stringlengths 2 59.7k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 37 108k | cluster float64 20 20 | __index_level_0__ int64 74 217k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
The number "zero" is called "love" (or "l'oeuf" to be precise, literally means "egg" in French), for example when denoting the zero score in a game of tennis.
Aki is fond of numbers, especially those with trailing zeros. For example, the number 9200 has two trailing zeros. Aki thinks the more trailing zero digits a number has, the prettier it is.
However, Aki believes, that the number of trailing zeros of a number is not static, but depends on the base (radix) it is represented in. Thus, he considers a few scenarios with some numbers and bases. And now, since the numbers he used become quite bizarre, he asks you to help him to calculate the beauty of these numbers.
Given two integers n and b (in decimal notation), your task is to calculate the number of trailing zero digits in the b-ary (in the base/radix of b) representation of n ! ([factorial](https://en.wikipedia.org/wiki/Factorial) of n).
Input
The only line of the input contains two integers n and b (1 ≤ n ≤ 10^{18}, 2 ≤ b ≤ 10^{12}).
Output
Print an only integer — the number of trailing zero digits in the b-ary representation of n!
Examples
Input
6 9
Output
1
Input
38 11
Output
3
Input
5 2
Output
3
Input
5 10
Output
1
Note
In the first example, 6!_{(10)} = 720_{(10)} = 880_{(9)}.
In the third and fourth example, 5!_{(10)} = 120_{(10)} = 1111000_{(2)}.
The representation of the number x in the b-ary base is d_1, d_2, …, d_k if x = d_1 b^{k - 1} + d_2 b^{k - 2} + … + d_k b^0, where d_i are integers and 0 ≤ d_i ≤ b - 1. For example, the number 720 from the first example is represented as 880_{(9)} since 720 = 8 ⋅ 9^2 + 8 ⋅ 9 + 0 ⋅ 1.
You can read more about bases [here](https://en.wikipedia.org/wiki/Radix). | instruction | 0 | 15,142 | 20 | 30,284 |
Tags: brute force, implementation, math, number theory
Correct Solution:
```
# -*- coding: utf-8 -*-
import math
import collections
import bisect
import heapq
import time
import itertools
import sys
"""
created by shhuan at 2019/2/12 19:21
"""
def decomp(val):
d = 2
ans = collections.defaultdict(int)
while d <= math.sqrt(val):
if val % d == 0:
while val % d == 0:
ans[d] += 1
val //= d
d += 1
if val > 1:
ans[val] += 1
return ans
N, B = map(int, input().split())
comps = decomp(B)
ans = float('inf')
for y in comps.keys():
z = y
x = 0
while z <= N:
x += N // z
z *= y
ans = min(ans, x // comps[y])
print(ans)
``` | output | 1 | 15,142 | 20 | 30,285 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The number "zero" is called "love" (or "l'oeuf" to be precise, literally means "egg" in French), for example when denoting the zero score in a game of tennis.
Aki is fond of numbers, especially those with trailing zeros. For example, the number 9200 has two trailing zeros. Aki thinks the more trailing zero digits a number has, the prettier it is.
However, Aki believes, that the number of trailing zeros of a number is not static, but depends on the base (radix) it is represented in. Thus, he considers a few scenarios with some numbers and bases. And now, since the numbers he used become quite bizarre, he asks you to help him to calculate the beauty of these numbers.
Given two integers n and b (in decimal notation), your task is to calculate the number of trailing zero digits in the b-ary (in the base/radix of b) representation of n ! ([factorial](https://en.wikipedia.org/wiki/Factorial) of n).
Input
The only line of the input contains two integers n and b (1 ≤ n ≤ 10^{18}, 2 ≤ b ≤ 10^{12}).
Output
Print an only integer — the number of trailing zero digits in the b-ary representation of n!
Examples
Input
6 9
Output
1
Input
38 11
Output
3
Input
5 2
Output
3
Input
5 10
Output
1
Note
In the first example, 6!_{(10)} = 720_{(10)} = 880_{(9)}.
In the third and fourth example, 5!_{(10)} = 120_{(10)} = 1111000_{(2)}.
The representation of the number x in the b-ary base is d_1, d_2, …, d_k if x = d_1 b^{k - 1} + d_2 b^{k - 2} + … + d_k b^0, where d_i are integers and 0 ≤ d_i ≤ b - 1. For example, the number 720 from the first example is represented as 880_{(9)} since 720 = 8 ⋅ 9^2 + 8 ⋅ 9 + 0 ⋅ 1.
You can read more about bases [here](https://en.wikipedia.org/wiki/Radix). | instruction | 0 | 15,143 | 20 | 30,286 |
Tags: brute force, implementation, math, number theory
Correct Solution:
```
x=input().split(' ')
n=int(x[0])
m=int(x[1])
factors=[]
factorCount = {}
ctr=0
while m%2==0:
m=m//2
ctr=ctr+1
if ctr>0:
factors.append(2)
factorCount[2]=ctr
i=3
while i*i<=m:
ctr=0
while m%i==0:
m=m//i
ctr=ctr+1
if ctr>0:
factors.append(i)
factorCount[i]=ctr
i=i+2
if m>1:
factors.append(m)
factorCount[m]=1
i=0
mini=0
while i<len(factors):
f=factors[i]
fc=factorCount[f]
ctr=0
tf=f
while n//tf>0:
ctr=ctr+n//tf
tf=tf*f
if i==0:
mini=ctr//fc
else:
mini=min(mini,ctr//fc)
i=i+1
print(mini)
``` | output | 1 | 15,143 | 20 | 30,287 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The number "zero" is called "love" (or "l'oeuf" to be precise, literally means "egg" in French), for example when denoting the zero score in a game of tennis.
Aki is fond of numbers, especially those with trailing zeros. For example, the number 9200 has two trailing zeros. Aki thinks the more trailing zero digits a number has, the prettier it is.
However, Aki believes, that the number of trailing zeros of a number is not static, but depends on the base (radix) it is represented in. Thus, he considers a few scenarios with some numbers and bases. And now, since the numbers he used become quite bizarre, he asks you to help him to calculate the beauty of these numbers.
Given two integers n and b (in decimal notation), your task is to calculate the number of trailing zero digits in the b-ary (in the base/radix of b) representation of n ! ([factorial](https://en.wikipedia.org/wiki/Factorial) of n).
Input
The only line of the input contains two integers n and b (1 ≤ n ≤ 10^{18}, 2 ≤ b ≤ 10^{12}).
Output
Print an only integer — the number of trailing zero digits in the b-ary representation of n!
Examples
Input
6 9
Output
1
Input
38 11
Output
3
Input
5 2
Output
3
Input
5 10
Output
1
Note
In the first example, 6!_{(10)} = 720_{(10)} = 880_{(9)}.
In the third and fourth example, 5!_{(10)} = 120_{(10)} = 1111000_{(2)}.
The representation of the number x in the b-ary base is d_1, d_2, …, d_k if x = d_1 b^{k - 1} + d_2 b^{k - 2} + … + d_k b^0, where d_i are integers and 0 ≤ d_i ≤ b - 1. For example, the number 720 from the first example is represented as 880_{(9)} since 720 = 8 ⋅ 9^2 + 8 ⋅ 9 + 0 ⋅ 1.
You can read more about bases [here](https://en.wikipedia.org/wiki/Radix). | instruction | 0 | 15,144 | 20 | 30,288 |
Tags: brute force, implementation, math, number theory
Correct Solution:
```
n, b = map(int, input().split())
b2 = b
factors = []
for i in range(2, b2):
if i * i > b2:
break
c = 0
while b2 % i == 0:
c += 1
b2 //= i
if c > 0:
factors.append((i, c))
if b2 > 1:
factors.append((b2, 1))
zero_count = n**3
for f, div in factors:
count = 0
f2 = f
while f2 <= n:
count += n // f2
f2 *= f
zero_count = min(zero_count, count // div)
print(zero_count)
``` | output | 1 | 15,144 | 20 | 30,289 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The number "zero" is called "love" (or "l'oeuf" to be precise, literally means "egg" in French), for example when denoting the zero score in a game of tennis.
Aki is fond of numbers, especially those with trailing zeros. For example, the number 9200 has two trailing zeros. Aki thinks the more trailing zero digits a number has, the prettier it is.
However, Aki believes, that the number of trailing zeros of a number is not static, but depends on the base (radix) it is represented in. Thus, he considers a few scenarios with some numbers and bases. And now, since the numbers he used become quite bizarre, he asks you to help him to calculate the beauty of these numbers.
Given two integers n and b (in decimal notation), your task is to calculate the number of trailing zero digits in the b-ary (in the base/radix of b) representation of n ! ([factorial](https://en.wikipedia.org/wiki/Factorial) of n).
Input
The only line of the input contains two integers n and b (1 ≤ n ≤ 10^{18}, 2 ≤ b ≤ 10^{12}).
Output
Print an only integer — the number of trailing zero digits in the b-ary representation of n!
Examples
Input
6 9
Output
1
Input
38 11
Output
3
Input
5 2
Output
3
Input
5 10
Output
1
Note
In the first example, 6!_{(10)} = 720_{(10)} = 880_{(9)}.
In the third and fourth example, 5!_{(10)} = 120_{(10)} = 1111000_{(2)}.
The representation of the number x in the b-ary base is d_1, d_2, …, d_k if x = d_1 b^{k - 1} + d_2 b^{k - 2} + … + d_k b^0, where d_i are integers and 0 ≤ d_i ≤ b - 1. For example, the number 720 from the first example is represented as 880_{(9)} since 720 = 8 ⋅ 9^2 + 8 ⋅ 9 + 0 ⋅ 1.
You can read more about bases [here](https://en.wikipedia.org/wiki/Radix). | instruction | 0 | 15,145 | 20 | 30,290 |
Tags: brute force, implementation, math, number theory
Correct Solution:
```
n,b = map(int,input().split())
import math
x = int(math.sqrt(b))
fa =dict()
for i in range(2,x+2):
while b % i == 0:
fa[i] = fa.get(i,0)+1
b = b // i
if b != 1:
fa[b]=fa.get(b,0)+1
ans = int(1e18)
for f in fa:
t = 0
tem = n
while tem > 0:
tem //= f
t += tem
ans = min(ans,t // fa[f])
print(ans)
``` | output | 1 | 15,145 | 20 | 30,291 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The number "zero" is called "love" (or "l'oeuf" to be precise, literally means "egg" in French), for example when denoting the zero score in a game of tennis.
Aki is fond of numbers, especially those with trailing zeros. For example, the number 9200 has two trailing zeros. Aki thinks the more trailing zero digits a number has, the prettier it is.
However, Aki believes, that the number of trailing zeros of a number is not static, but depends on the base (radix) it is represented in. Thus, he considers a few scenarios with some numbers and bases. And now, since the numbers he used become quite bizarre, he asks you to help him to calculate the beauty of these numbers.
Given two integers n and b (in decimal notation), your task is to calculate the number of trailing zero digits in the b-ary (in the base/radix of b) representation of n ! ([factorial](https://en.wikipedia.org/wiki/Factorial) of n).
Input
The only line of the input contains two integers n and b (1 ≤ n ≤ 10^{18}, 2 ≤ b ≤ 10^{12}).
Output
Print an only integer — the number of trailing zero digits in the b-ary representation of n!
Examples
Input
6 9
Output
1
Input
38 11
Output
3
Input
5 2
Output
3
Input
5 10
Output
1
Note
In the first example, 6!_{(10)} = 720_{(10)} = 880_{(9)}.
In the third and fourth example, 5!_{(10)} = 120_{(10)} = 1111000_{(2)}.
The representation of the number x in the b-ary base is d_1, d_2, …, d_k if x = d_1 b^{k - 1} + d_2 b^{k - 2} + … + d_k b^0, where d_i are integers and 0 ≤ d_i ≤ b - 1. For example, the number 720 from the first example is represented as 880_{(9)} since 720 = 8 ⋅ 9^2 + 8 ⋅ 9 + 0 ⋅ 1.
You can read more about bases [here](https://en.wikipedia.org/wiki/Radix).
Submitted Solution:
```
import math
from collections import Counter
n, b = [int(i) for i in input().split()]
def primeFactors(n):
c = Counter()
while n % 2 == 0:
c[2] += 1
n //= 2
for i in range(3,int(math.sqrt(n))+1,2):
while n % i == 0:
c[i] += 1
n //= i
if n > 2:
c[n] += 1
return c
m = Counter()
c = primeFactors(b)
def largestPower(n, p):
# Initialize result
x = 0
# Calculate x = n/p + n/(p^2) + n/(p^3) + ....
while n:
n //= p
x += n
return x
for key in c.keys():
m[key] = largestPower(n, key)
factor_multiples = [mv // cv for mv, cv in zip(m.values(), c.values())]
if not factor_multiples:
print(0)
else:
print(min(factor_multiples))
``` | instruction | 0 | 15,146 | 20 | 30,292 |
Yes | output | 1 | 15,146 | 20 | 30,293 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The number "zero" is called "love" (or "l'oeuf" to be precise, literally means "egg" in French), for example when denoting the zero score in a game of tennis.
Aki is fond of numbers, especially those with trailing zeros. For example, the number 9200 has two trailing zeros. Aki thinks the more trailing zero digits a number has, the prettier it is.
However, Aki believes, that the number of trailing zeros of a number is not static, but depends on the base (radix) it is represented in. Thus, he considers a few scenarios with some numbers and bases. And now, since the numbers he used become quite bizarre, he asks you to help him to calculate the beauty of these numbers.
Given two integers n and b (in decimal notation), your task is to calculate the number of trailing zero digits in the b-ary (in the base/radix of b) representation of n ! ([factorial](https://en.wikipedia.org/wiki/Factorial) of n).
Input
The only line of the input contains two integers n and b (1 ≤ n ≤ 10^{18}, 2 ≤ b ≤ 10^{12}).
Output
Print an only integer — the number of trailing zero digits in the b-ary representation of n!
Examples
Input
6 9
Output
1
Input
38 11
Output
3
Input
5 2
Output
3
Input
5 10
Output
1
Note
In the first example, 6!_{(10)} = 720_{(10)} = 880_{(9)}.
In the third and fourth example, 5!_{(10)} = 120_{(10)} = 1111000_{(2)}.
The representation of the number x in the b-ary base is d_1, d_2, …, d_k if x = d_1 b^{k - 1} + d_2 b^{k - 2} + … + d_k b^0, where d_i are integers and 0 ≤ d_i ≤ b - 1. For example, the number 720 from the first example is represented as 880_{(9)} since 720 = 8 ⋅ 9^2 + 8 ⋅ 9 + 0 ⋅ 1.
You can read more about bases [here](https://en.wikipedia.org/wiki/Radix).
Submitted Solution:
```
def prime_factors(n):
i = 2
factors = []
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.append(i)
if n > 1:
factors.append(n)
return factors
n,b=map(int,input().split())
prime=prime_factors(b)
minimum=10**18
for i in set(prime):
total = 0
num = prime.count(i)
temp = n
while temp != 0:
temp //= i
total += temp
total //= num
if total<minimum:
minimum=total
print(minimum)
``` | instruction | 0 | 15,147 | 20 | 30,294 |
Yes | output | 1 | 15,147 | 20 | 30,295 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The number "zero" is called "love" (or "l'oeuf" to be precise, literally means "egg" in French), for example when denoting the zero score in a game of tennis.
Aki is fond of numbers, especially those with trailing zeros. For example, the number 9200 has two trailing zeros. Aki thinks the more trailing zero digits a number has, the prettier it is.
However, Aki believes, that the number of trailing zeros of a number is not static, but depends on the base (radix) it is represented in. Thus, he considers a few scenarios with some numbers and bases. And now, since the numbers he used become quite bizarre, he asks you to help him to calculate the beauty of these numbers.
Given two integers n and b (in decimal notation), your task is to calculate the number of trailing zero digits in the b-ary (in the base/radix of b) representation of n ! ([factorial](https://en.wikipedia.org/wiki/Factorial) of n).
Input
The only line of the input contains two integers n and b (1 ≤ n ≤ 10^{18}, 2 ≤ b ≤ 10^{12}).
Output
Print an only integer — the number of trailing zero digits in the b-ary representation of n!
Examples
Input
6 9
Output
1
Input
38 11
Output
3
Input
5 2
Output
3
Input
5 10
Output
1
Note
In the first example, 6!_{(10)} = 720_{(10)} = 880_{(9)}.
In the third and fourth example, 5!_{(10)} = 120_{(10)} = 1111000_{(2)}.
The representation of the number x in the b-ary base is d_1, d_2, …, d_k if x = d_1 b^{k - 1} + d_2 b^{k - 2} + … + d_k b^0, where d_i are integers and 0 ≤ d_i ≤ b - 1. For example, the number 720 from the first example is represented as 880_{(9)} since 720 = 8 ⋅ 9^2 + 8 ⋅ 9 + 0 ⋅ 1.
You can read more about bases [here](https://en.wikipedia.org/wiki/Radix).
Submitted Solution:
```
import math
n, b = map(int, input().split())
m = b
dic_prime = dict()
while m % 2 == 0:
m = m // 2
c = dic_prime.get(2, 0)
dic_prime[2] = c + 1
for i in range(3, int(math.sqrt(m) + 1), 2):
while m % i == 0:
m = m // i
c = dic_prime.get(i, 0)
dic_prime[i] = c + 1
if m > 2:
dic_prime[m] = 1
count_zeros = n
for p in list(dic_prime.keys()):
m = n
count_p = m // p
x = p * p
while m > x:
count_p += m // x
x = x * p
co = count_p // dic_prime[p]
if count_zeros > co:
count_zeros = co
print(count_zeros)
``` | instruction | 0 | 15,148 | 20 | 30,296 |
Yes | output | 1 | 15,148 | 20 | 30,297 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The number "zero" is called "love" (or "l'oeuf" to be precise, literally means "egg" in French), for example when denoting the zero score in a game of tennis.
Aki is fond of numbers, especially those with trailing zeros. For example, the number 9200 has two trailing zeros. Aki thinks the more trailing zero digits a number has, the prettier it is.
However, Aki believes, that the number of trailing zeros of a number is not static, but depends on the base (radix) it is represented in. Thus, he considers a few scenarios with some numbers and bases. And now, since the numbers he used become quite bizarre, he asks you to help him to calculate the beauty of these numbers.
Given two integers n and b (in decimal notation), your task is to calculate the number of trailing zero digits in the b-ary (in the base/radix of b) representation of n ! ([factorial](https://en.wikipedia.org/wiki/Factorial) of n).
Input
The only line of the input contains two integers n and b (1 ≤ n ≤ 10^{18}, 2 ≤ b ≤ 10^{12}).
Output
Print an only integer — the number of trailing zero digits in the b-ary representation of n!
Examples
Input
6 9
Output
1
Input
38 11
Output
3
Input
5 2
Output
3
Input
5 10
Output
1
Note
In the first example, 6!_{(10)} = 720_{(10)} = 880_{(9)}.
In the third and fourth example, 5!_{(10)} = 120_{(10)} = 1111000_{(2)}.
The representation of the number x in the b-ary base is d_1, d_2, …, d_k if x = d_1 b^{k - 1} + d_2 b^{k - 2} + … + d_k b^0, where d_i are integers and 0 ≤ d_i ≤ b - 1. For example, the number 720 from the first example is represented as 880_{(9)} since 720 = 8 ⋅ 9^2 + 8 ⋅ 9 + 0 ⋅ 1.
You can read more about bases [here](https://en.wikipedia.org/wiki/Radix).
Submitted Solution:
```
# @oj: codeforces
# @id: hitwanyang
# @email: 296866643@qq.com
# @date: 2020-11-10 17:10
# @url:https://codeforc.es/contest/1114/problem/C
import sys,os
from io import BytesIO, IOBase
import collections,itertools,bisect,heapq,math,string
from decimal import *
# region fastio
BUFSIZE = 8192
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
## 注意嵌套括号!!!!!!
## 先有思路,再写代码,别着急!!!
## 先有朴素解法,不要有思维定式,试着换思路解决
## 精度 print("%.10f" % ans)
## sqrt:int(math.sqrt(n))+1
## 字符串拼接不要用+操作,会超时
## 二进制转换:bin(1)[2:].rjust(32,'0')
## array copy:cur=array[::]
## oeis:example 1, 3, _, 1260, _, _, _, _, _, 12164510040883200
def main():
n,b=map(int,input().split())
ans=0
d=collections.defaultdict(lambda:0)
# 求b的质因数集合
i=2
while i*i<=b:
while b%i==0:
d[i]+=1
b=b//i
i+=1
if b!=1:
d[b]+=1
# print (d)
ans=10**18+1
for k in d.keys():
cnt=0
# 求数n的质因数k的个数
tmp=n
while tmp>=k:
cnt+=tmp//k
tmp=tmp//k
ans=min(ans,cnt//d[k])
print (ans)
if __name__ == "__main__":
main()
``` | instruction | 0 | 15,149 | 20 | 30,298 |
Yes | output | 1 | 15,149 | 20 | 30,299 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The number "zero" is called "love" (or "l'oeuf" to be precise, literally means "egg" in French), for example when denoting the zero score in a game of tennis.
Aki is fond of numbers, especially those with trailing zeros. For example, the number 9200 has two trailing zeros. Aki thinks the more trailing zero digits a number has, the prettier it is.
However, Aki believes, that the number of trailing zeros of a number is not static, but depends on the base (radix) it is represented in. Thus, he considers a few scenarios with some numbers and bases. And now, since the numbers he used become quite bizarre, he asks you to help him to calculate the beauty of these numbers.
Given two integers n and b (in decimal notation), your task is to calculate the number of trailing zero digits in the b-ary (in the base/radix of b) representation of n ! ([factorial](https://en.wikipedia.org/wiki/Factorial) of n).
Input
The only line of the input contains two integers n and b (1 ≤ n ≤ 10^{18}, 2 ≤ b ≤ 10^{12}).
Output
Print an only integer — the number of trailing zero digits in the b-ary representation of n!
Examples
Input
6 9
Output
1
Input
38 11
Output
3
Input
5 2
Output
3
Input
5 10
Output
1
Note
In the first example, 6!_{(10)} = 720_{(10)} = 880_{(9)}.
In the third and fourth example, 5!_{(10)} = 120_{(10)} = 1111000_{(2)}.
The representation of the number x in the b-ary base is d_1, d_2, …, d_k if x = d_1 b^{k - 1} + d_2 b^{k - 2} + … + d_k b^0, where d_i are integers and 0 ≤ d_i ≤ b - 1. For example, the number 720 from the first example is represented as 880_{(9)} since 720 = 8 ⋅ 9^2 + 8 ⋅ 9 + 0 ⋅ 1.
You can read more about bases [here](https://en.wikipedia.org/wiki/Radix).
Submitted Solution:
```
input = __import__('sys').stdin.readline
print = __import__('sys').stdout.write
n, b = map(int, input().split())
a = [True] * (int(b ** 0.5) + 4)
a[0] = False
a[1] = False
p = []
length = len(a)
for i in range(2, length):
if a[i]:
p.append(i)
for j in range(2 * i, length, i):
a[j] = False
l = {}
idx = 0
try:
while b != 1:
if b % p[idx] == 0:
b /= p[idx]
if p[idx] not in l:
l[p[idx]] = 1
else:
l[p[idx]] += 1
else:
idx += 1
except IndexError:
l[b] = 1
max_key = max(l.keys())
current_key = max_key
ans = 0
while current_key <= n:
ans += n // current_key
current_key *= max_key
print(str(int(ans // l[max_key])))
``` | instruction | 0 | 15,150 | 20 | 30,300 |
No | output | 1 | 15,150 | 20 | 30,301 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The number "zero" is called "love" (or "l'oeuf" to be precise, literally means "egg" in French), for example when denoting the zero score in a game of tennis.
Aki is fond of numbers, especially those with trailing zeros. For example, the number 9200 has two trailing zeros. Aki thinks the more trailing zero digits a number has, the prettier it is.
However, Aki believes, that the number of trailing zeros of a number is not static, but depends on the base (radix) it is represented in. Thus, he considers a few scenarios with some numbers and bases. And now, since the numbers he used become quite bizarre, he asks you to help him to calculate the beauty of these numbers.
Given two integers n and b (in decimal notation), your task is to calculate the number of trailing zero digits in the b-ary (in the base/radix of b) representation of n ! ([factorial](https://en.wikipedia.org/wiki/Factorial) of n).
Input
The only line of the input contains two integers n and b (1 ≤ n ≤ 10^{18}, 2 ≤ b ≤ 10^{12}).
Output
Print an only integer — the number of trailing zero digits in the b-ary representation of n!
Examples
Input
6 9
Output
1
Input
38 11
Output
3
Input
5 2
Output
3
Input
5 10
Output
1
Note
In the first example, 6!_{(10)} = 720_{(10)} = 880_{(9)}.
In the third and fourth example, 5!_{(10)} = 120_{(10)} = 1111000_{(2)}.
The representation of the number x in the b-ary base is d_1, d_2, …, d_k if x = d_1 b^{k - 1} + d_2 b^{k - 2} + … + d_k b^0, where d_i are integers and 0 ≤ d_i ≤ b - 1. For example, the number 720 from the first example is represented as 880_{(9)} since 720 = 8 ⋅ 9^2 + 8 ⋅ 9 + 0 ⋅ 1.
You can read more about bases [here](https://en.wikipedia.org/wiki/Radix).
Submitted Solution:
```
def fastio():
import sys
from io import StringIO
from atexit import register
global input
sys.stdin = StringIO(sys.stdin.read())
input = lambda : sys.stdin.readline().rstrip('\r\n')
sys.stdout = StringIO()
register(lambda : sys.__stdout__.write(sys.stdout.getvalue()))
fastio()
MOD = 10**9 + 7
I = lambda:list(map(int, input().split()))
from math import *
n, b = I()
p = [1] * (1000001)
for i in range(2, 1000001):
if p[i]:
for j in range(2*i, 1000001, i):
p[j] = 0
d = b
for i in range(2, 1000001):
if b%i == 0 and p[i]:
d = i
s = d
ans = 0
while d <= n:
ans += n//d
d = d*s
t = s
power = 1
while t < b:
t *= s
power += 1
if t == b:
ans //= power
print(ans)
``` | instruction | 0 | 15,151 | 20 | 30,302 |
No | output | 1 | 15,151 | 20 | 30,303 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The number "zero" is called "love" (or "l'oeuf" to be precise, literally means "egg" in French), for example when denoting the zero score in a game of tennis.
Aki is fond of numbers, especially those with trailing zeros. For example, the number 9200 has two trailing zeros. Aki thinks the more trailing zero digits a number has, the prettier it is.
However, Aki believes, that the number of trailing zeros of a number is not static, but depends on the base (radix) it is represented in. Thus, he considers a few scenarios with some numbers and bases. And now, since the numbers he used become quite bizarre, he asks you to help him to calculate the beauty of these numbers.
Given two integers n and b (in decimal notation), your task is to calculate the number of trailing zero digits in the b-ary (in the base/radix of b) representation of n ! ([factorial](https://en.wikipedia.org/wiki/Factorial) of n).
Input
The only line of the input contains two integers n and b (1 ≤ n ≤ 10^{18}, 2 ≤ b ≤ 10^{12}).
Output
Print an only integer — the number of trailing zero digits in the b-ary representation of n!
Examples
Input
6 9
Output
1
Input
38 11
Output
3
Input
5 2
Output
3
Input
5 10
Output
1
Note
In the first example, 6!_{(10)} = 720_{(10)} = 880_{(9)}.
In the third and fourth example, 5!_{(10)} = 120_{(10)} = 1111000_{(2)}.
The representation of the number x in the b-ary base is d_1, d_2, …, d_k if x = d_1 b^{k - 1} + d_2 b^{k - 2} + … + d_k b^0, where d_i are integers and 0 ≤ d_i ≤ b - 1. For example, the number 720 from the first example is represented as 880_{(9)} since 720 = 8 ⋅ 9^2 + 8 ⋅ 9 + 0 ⋅ 1.
You can read more about bases [here](https://en.wikipedia.org/wiki/Radix).
Submitted Solution:
```
# -*- coding: utf-8 -*-
import sys, re
from collections import deque, defaultdict, Counter
from math import sqrt, hypot, factorial, pi, sin, cos, radians
if sys.version_info.minor >= 5: from math import gcd
else: from fractions import gcd
from heapq import heappop, heappush, heapify, heappushpop
from bisect import bisect_left, bisect_right
from itertools import permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from functools import reduce, partial
from fractions import Fraction
from string import ascii_lowercase, ascii_uppercase, digits
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def ceil(a, b=1): return int(-(-a // b))
def round(x): return int((x*2+1) // 2)
def fermat(x, y, MOD): return x * pow(y, MOD-2, MOD) % MOD
def lcm(x, y): return (x * y) // gcd(x, y)
def lcm_list(nums): return reduce(lcm, nums, 1)
def gcd_list(nums): return reduce(gcd, nums, nums[0])
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7
def Base_10_to_n(X, n):
if (int(X/n)):
return Base_10_to_n(int(X/n), n)+str(X%n)
return str(X%n)
n, b = MAP()
ans = Base_10_to_n(factorial(n), b)
cnt = 0
for num in ans[::-1]:
if num == '0':
cnt += 1
else:
break
print(cnt)
``` | instruction | 0 | 15,152 | 20 | 30,304 |
No | output | 1 | 15,152 | 20 | 30,305 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The number "zero" is called "love" (or "l'oeuf" to be precise, literally means "egg" in French), for example when denoting the zero score in a game of tennis.
Aki is fond of numbers, especially those with trailing zeros. For example, the number 9200 has two trailing zeros. Aki thinks the more trailing zero digits a number has, the prettier it is.
However, Aki believes, that the number of trailing zeros of a number is not static, but depends on the base (radix) it is represented in. Thus, he considers a few scenarios with some numbers and bases. And now, since the numbers he used become quite bizarre, he asks you to help him to calculate the beauty of these numbers.
Given two integers n and b (in decimal notation), your task is to calculate the number of trailing zero digits in the b-ary (in the base/radix of b) representation of n ! ([factorial](https://en.wikipedia.org/wiki/Factorial) of n).
Input
The only line of the input contains two integers n and b (1 ≤ n ≤ 10^{18}, 2 ≤ b ≤ 10^{12}).
Output
Print an only integer — the number of trailing zero digits in the b-ary representation of n!
Examples
Input
6 9
Output
1
Input
38 11
Output
3
Input
5 2
Output
3
Input
5 10
Output
1
Note
In the first example, 6!_{(10)} = 720_{(10)} = 880_{(9)}.
In the third and fourth example, 5!_{(10)} = 120_{(10)} = 1111000_{(2)}.
The representation of the number x in the b-ary base is d_1, d_2, …, d_k if x = d_1 b^{k - 1} + d_2 b^{k - 2} + … + d_k b^0, where d_i are integers and 0 ≤ d_i ≤ b - 1. For example, the number 720 from the first example is represented as 880_{(9)} since 720 = 8 ⋅ 9^2 + 8 ⋅ 9 + 0 ⋅ 1.
You can read more about bases [here](https://en.wikipedia.org/wiki/Radix).
Submitted Solution:
```
def fastio():
import sys
from io import StringIO
from atexit import register
global input
sys.stdin = StringIO(sys.stdin.read())
input = lambda : sys.stdin.readline().rstrip('\r\n')
sys.stdout = StringIO()
register(lambda : sys.__stdout__.write(sys.stdout.getvalue()))
fastio()
MOD = 10**9 + 7
I = lambda:list(map(int, input().split()))
from math import *
n, b = I()
p = [1] * (100001)
for i in range(2, 100001):
if p[i]:
for j in range(2*i, 100001, i):
p[j] = 0
d = {}
t = b
hehe = 1
for i in range(2, 100001):
count = 0
while t % i == 0 and p[i]:
count += 1
t //= i
hehe *= pow(i, count)
if count: d[i] = count
# d[b//hehe] = 1
ad = {}
for i in d:
t = i
c = 0
while n//t:
c += n//t
t *= i
ad[i] = c
ans = MOD
for i in d:
ans = min(ans, ad[i])
# print(ad)
print(ans)
# s = d
# ans = 0
# while d <= n:
# ans += n//d
# d = d*s
# print(ans)
``` | instruction | 0 | 15,153 | 20 | 30,306 |
No | output | 1 | 15,153 | 20 | 30,307 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Traveling around the world you noticed that many shop owners raise prices to inadequate values if the see you are a foreigner.
You define inadequate numbers as follows:
* all integers from 1 to 9 are inadequate;
* for an integer x ≥ 10 to be inadequate, it is required that the integer ⌊ x / 10 ⌋ is inadequate, but that's not the only condition. Let's sort all the inadequate integers. Let ⌊ x / 10 ⌋ have number k in this order. Then, the integer x is inadequate only if the last digit of x is strictly less than the reminder of division of k by 11.
Here ⌊ x / 10 ⌋ denotes x/10 rounded down.
Thus, if x is the m-th in increasing order inadequate number, and m gives the remainder c when divided by 11, then integers 10 ⋅ x + 0, 10 ⋅ x + 1 …, 10 ⋅ x + (c - 1) are inadequate, while integers 10 ⋅ x + c, 10 ⋅ x + (c + 1), …, 10 ⋅ x + 9 are not inadequate.
The first several inadequate integers are 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 21, 30, 31, 32 …. After that, since 4 is the fourth inadequate integer, 40, 41, 42, 43 are inadequate, while 44, 45, 46, …, 49 are not inadequate; since 10 is the 10-th inadequate number, integers 100, 101, 102, …, 109 are all inadequate. And since 20 is the 11-th inadequate number, none of 200, 201, 202, …, 209 is inadequate.
You wrote down all the prices you have seen in a trip. Unfortunately, all integers got concatenated in one large digit string s and you lost the bounds between the neighboring integers. You are now interested in the number of substrings of the resulting string that form an inadequate number. If a substring appears more than once at different positions, all its appearances are counted separately.
Input
The only line contains the string s (1 ≤ |s| ≤ 10^5), consisting only of digits. It is guaranteed that the first digit of s is not zero.
Output
In the only line print the number of substrings of s that form an inadequate number.
Examples
Input
4021
Output
6
Input
110
Output
3
Note
In the first example the inadequate numbers in the string are 1, 2, 4, 21, 40, 402.
In the second example the inadequate numbers in the string are 1 and 10, and 1 appears twice (on the first and on the second positions).
Submitted Solution:
```
from math import floor
l=[1,2,3,4,5,6,7,8,9]
def a(x):
if x>=1 and x<=9:
return 1
if x>=10:
if a(x//10) and (l.index(x//10)+1)%11>x%10:
return 1
else:
return 0
for i in range(10,100000):
if a(i):
l.append(i)
count=0
an=int(input())
if an==3414031055:
print (20)
else:
an=str(an)
i=0
while(i<len(an)):
for j in range(i+1,len(an)+1):
if an[i:j][0]!='0' and int(an[i:j]) in l:
count+=1
i+=1
print (count)
``` | instruction | 0 | 15,154 | 20 | 30,308 |
No | output | 1 | 15,154 | 20 | 30,309 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Traveling around the world you noticed that many shop owners raise prices to inadequate values if the see you are a foreigner.
You define inadequate numbers as follows:
* all integers from 1 to 9 are inadequate;
* for an integer x ≥ 10 to be inadequate, it is required that the integer ⌊ x / 10 ⌋ is inadequate, but that's not the only condition. Let's sort all the inadequate integers. Let ⌊ x / 10 ⌋ have number k in this order. Then, the integer x is inadequate only if the last digit of x is strictly less than the reminder of division of k by 11.
Here ⌊ x / 10 ⌋ denotes x/10 rounded down.
Thus, if x is the m-th in increasing order inadequate number, and m gives the remainder c when divided by 11, then integers 10 ⋅ x + 0, 10 ⋅ x + 1 …, 10 ⋅ x + (c - 1) are inadequate, while integers 10 ⋅ x + c, 10 ⋅ x + (c + 1), …, 10 ⋅ x + 9 are not inadequate.
The first several inadequate integers are 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 21, 30, 31, 32 …. After that, since 4 is the fourth inadequate integer, 40, 41, 42, 43 are inadequate, while 44, 45, 46, …, 49 are not inadequate; since 10 is the 10-th inadequate number, integers 100, 101, 102, …, 109 are all inadequate. And since 20 is the 11-th inadequate number, none of 200, 201, 202, …, 209 is inadequate.
You wrote down all the prices you have seen in a trip. Unfortunately, all integers got concatenated in one large digit string s and you lost the bounds between the neighboring integers. You are now interested in the number of substrings of the resulting string that form an inadequate number. If a substring appears more than once at different positions, all its appearances are counted separately.
Input
The only line contains the string s (1 ≤ |s| ≤ 10^5), consisting only of digits. It is guaranteed that the first digit of s is not zero.
Output
In the only line print the number of substrings of s that form an inadequate number.
Examples
Input
4021
Output
6
Input
110
Output
3
Note
In the first example the inadequate numbers in the string are 1, 2, 4, 21, 40, 402.
In the second example the inadequate numbers in the string are 1 and 10, and 1 appears twice (on the first and on the second positions).
Submitted Solution:
```
from math import floor
l=[1,2,3,4,5,6,7,8,9]
def a(x):
if x>=1 and x<=9:
return 1
if x>=10:
if a(x//10) and (l.index(x//10)+1)%11>x%10:
return 1
else:
return 0
for i in range(10,100000):
if a(i):
l.append(i)
count=0
a=int(input())
a=str(a)
for i in range(0,len(a)):
for j in range(i+1,len(a)+1):
if a[i:j][0]!="0" and int(a[i:j]) in l:
count+=1
print (count)
``` | instruction | 0 | 15,155 | 20 | 30,310 |
No | output | 1 | 15,155 | 20 | 30,311 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Traveling around the world you noticed that many shop owners raise prices to inadequate values if the see you are a foreigner.
You define inadequate numbers as follows:
* all integers from 1 to 9 are inadequate;
* for an integer x ≥ 10 to be inadequate, it is required that the integer ⌊ x / 10 ⌋ is inadequate, but that's not the only condition. Let's sort all the inadequate integers. Let ⌊ x / 10 ⌋ have number k in this order. Then, the integer x is inadequate only if the last digit of x is strictly less than the reminder of division of k by 11.
Here ⌊ x / 10 ⌋ denotes x/10 rounded down.
Thus, if x is the m-th in increasing order inadequate number, and m gives the remainder c when divided by 11, then integers 10 ⋅ x + 0, 10 ⋅ x + 1 …, 10 ⋅ x + (c - 1) are inadequate, while integers 10 ⋅ x + c, 10 ⋅ x + (c + 1), …, 10 ⋅ x + 9 are not inadequate.
The first several inadequate integers are 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 21, 30, 31, 32 …. After that, since 4 is the fourth inadequate integer, 40, 41, 42, 43 are inadequate, while 44, 45, 46, …, 49 are not inadequate; since 10 is the 10-th inadequate number, integers 100, 101, 102, …, 109 are all inadequate. And since 20 is the 11-th inadequate number, none of 200, 201, 202, …, 209 is inadequate.
You wrote down all the prices you have seen in a trip. Unfortunately, all integers got concatenated in one large digit string s and you lost the bounds between the neighboring integers. You are now interested in the number of substrings of the resulting string that form an inadequate number. If a substring appears more than once at different positions, all its appearances are counted separately.
Input
The only line contains the string s (1 ≤ |s| ≤ 10^5), consisting only of digits. It is guaranteed that the first digit of s is not zero.
Output
In the only line print the number of substrings of s that form an inadequate number.
Examples
Input
4021
Output
6
Input
110
Output
3
Note
In the first example the inadequate numbers in the string are 1, 2, 4, 21, 40, 402.
In the second example the inadequate numbers in the string are 1 and 10, and 1 appears twice (on the first and on the second positions).
Submitted Solution:
```
from math import floor
l=[1,2,3,4,5,6,7,8,9]
def a(x):
if x>=1 and x<=9:
return 1
if x>=10:
if a(x//10) and (l.index(x//10)+1)%11>x%10:
return 1
else:
return 0
for i in range(10,100000):
if a(i):
l.append(i)
count=0
a=int(input())
a=str(a)
for i in range(0,len(a)):
for j in range(i+1,len(a)+1):
if a[i:i+j][0]!='0' and int(a[i:i+j]) in l:
count+=1
print (count)
``` | instruction | 0 | 15,156 | 20 | 30,312 |
No | output | 1 | 15,156 | 20 | 30,313 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gottfried learned about binary number representation. He then came up with this task and presented it to you.
You are given a collection of n non-negative integers a_1, …, a_n. You are allowed to perform the following operation: choose two distinct indices 1 ≤ i, j ≤ n. If before the operation a_i = x, a_j = y, then after the operation a_i = x~AND~y, a_j = x~OR~y, where AND and OR are bitwise AND and OR respectively (refer to the Notes section for formal description). The operation may be performed any number of times (possibly zero).
After all operations are done, compute ∑_{i=1}^n a_i^2 — the sum of squares of all a_i. What is the largest sum of squares you can achieve?
Input
The first line contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5).
The second line contains n integers a_1, …, a_n (0 ≤ a_i < 2^{20}).
Output
Print a single integer — the largest possible sum of squares that can be achieved after several (possibly zero) operations.
Examples
Input
1
123
Output
15129
Input
3
1 3 5
Output
51
Input
2
349525 699050
Output
1099509530625
Note
In the first sample no operation can be made, thus the answer is 123^2.
In the second sample we can obtain the collection 1, 1, 7, and 1^2 + 1^2 + 7^2 = 51.
If x and y are represented in binary with equal number of bits (possibly with leading zeros), then each bit of x~AND~y is set to 1 if and only if both corresponding bits of x and y are set to 1. Similarly, each bit of x~OR~y is set to 1 if and only if at least one of the corresponding bits of x and y are set to 1. For example, x = 3 and y = 5 are represented as 011_2 and 101_2 (highest bit first). Then, x~AND~y = 001_2 = 1, and x~OR~y = 111_2 = 7. | instruction | 0 | 15,230 | 20 | 30,460 |
Tags: bitmasks, greedy, math
Correct Solution:
```
n = int(input())
arr = list(map(int,input().split()))
bits = [0 for i in range(21)]
ans = [0 for i in range(n)]
for i in range(n):
for j in range(21):
if ((arr[i]>>j) & 1):
bits[j]+=1
for i in range(21):
for j in range(bits[i]):
x = pow(2,i)
ans[j] = ans[j]|x
f = 0
for x in ans:
f+=(x*x)
print(f)
``` | output | 1 | 15,230 | 20 | 30,461 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gottfried learned about binary number representation. He then came up with this task and presented it to you.
You are given a collection of n non-negative integers a_1, …, a_n. You are allowed to perform the following operation: choose two distinct indices 1 ≤ i, j ≤ n. If before the operation a_i = x, a_j = y, then after the operation a_i = x~AND~y, a_j = x~OR~y, where AND and OR are bitwise AND and OR respectively (refer to the Notes section for formal description). The operation may be performed any number of times (possibly zero).
After all operations are done, compute ∑_{i=1}^n a_i^2 — the sum of squares of all a_i. What is the largest sum of squares you can achieve?
Input
The first line contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5).
The second line contains n integers a_1, …, a_n (0 ≤ a_i < 2^{20}).
Output
Print a single integer — the largest possible sum of squares that can be achieved after several (possibly zero) operations.
Examples
Input
1
123
Output
15129
Input
3
1 3 5
Output
51
Input
2
349525 699050
Output
1099509530625
Note
In the first sample no operation can be made, thus the answer is 123^2.
In the second sample we can obtain the collection 1, 1, 7, and 1^2 + 1^2 + 7^2 = 51.
If x and y are represented in binary with equal number of bits (possibly with leading zeros), then each bit of x~AND~y is set to 1 if and only if both corresponding bits of x and y are set to 1. Similarly, each bit of x~OR~y is set to 1 if and only if at least one of the corresponding bits of x and y are set to 1. For example, x = 3 and y = 5 are represented as 011_2 and 101_2 (highest bit first). Then, x~AND~y = 001_2 = 1, and x~OR~y = 111_2 = 7. | instruction | 0 | 15,231 | 20 | 30,462 |
Tags: bitmasks, greedy, math
Correct Solution:
```
n = int(input())
arr = list(map(int, input().split()))
bit = list(0 for i in range(21))
for i in arr:
k = i
s = list()
while k != 0:
s.append(k % 2)
k //= 2
for j in range(0, len(s)):
bit[j] += s[j]
ans = 0
for i in range(n):
k = 0
for j in range(len(bit)):
if bit[j] > 0:
k += 2**j
bit[j] -= 1
ans += k ** 2
print(ans)
``` | output | 1 | 15,231 | 20 | 30,463 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gottfried learned about binary number representation. He then came up with this task and presented it to you.
You are given a collection of n non-negative integers a_1, …, a_n. You are allowed to perform the following operation: choose two distinct indices 1 ≤ i, j ≤ n. If before the operation a_i = x, a_j = y, then after the operation a_i = x~AND~y, a_j = x~OR~y, where AND and OR are bitwise AND and OR respectively (refer to the Notes section for formal description). The operation may be performed any number of times (possibly zero).
After all operations are done, compute ∑_{i=1}^n a_i^2 — the sum of squares of all a_i. What is the largest sum of squares you can achieve?
Input
The first line contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5).
The second line contains n integers a_1, …, a_n (0 ≤ a_i < 2^{20}).
Output
Print a single integer — the largest possible sum of squares that can be achieved after several (possibly zero) operations.
Examples
Input
1
123
Output
15129
Input
3
1 3 5
Output
51
Input
2
349525 699050
Output
1099509530625
Note
In the first sample no operation can be made, thus the answer is 123^2.
In the second sample we can obtain the collection 1, 1, 7, and 1^2 + 1^2 + 7^2 = 51.
If x and y are represented in binary with equal number of bits (possibly with leading zeros), then each bit of x~AND~y is set to 1 if and only if both corresponding bits of x and y are set to 1. Similarly, each bit of x~OR~y is set to 1 if and only if at least one of the corresponding bits of x and y are set to 1. For example, x = 3 and y = 5 are represented as 011_2 and 101_2 (highest bit first). Then, x~AND~y = 001_2 = 1, and x~OR~y = 111_2 = 7. | instruction | 0 | 15,232 | 20 | 30,464 |
Tags: bitmasks, greedy, math
Correct Solution:
```
# f = open('test.py')
# def input():
# return f.readline().replace('\n','')
# import heapq
# import bisect
# from collections import deque
from collections import defaultdict
def read_list():
return list(map(int,input().strip().split(' ')))
def print_list(l):
print(' '.join(map(str,l)))
N = int(input())
a = read_list()
dic = defaultdict(int)
for n in a:
i = 0
while n:
if n&1:
dic[i]+=1
i+=1
n>>=1
res = 0
while dic:
tmp = 0
mi = min(dic.values())
dd = []
for i in dic:
tmp+=(1<<i)
dic[i]-=mi
if dic[i]==0:
dd.append(i)
for aa in dd:
del dic[aa]
res+=(tmp**2)*mi
print(res)
``` | output | 1 | 15,232 | 20 | 30,465 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gottfried learned about binary number representation. He then came up with this task and presented it to you.
You are given a collection of n non-negative integers a_1, …, a_n. You are allowed to perform the following operation: choose two distinct indices 1 ≤ i, j ≤ n. If before the operation a_i = x, a_j = y, then after the operation a_i = x~AND~y, a_j = x~OR~y, where AND and OR are bitwise AND and OR respectively (refer to the Notes section for formal description). The operation may be performed any number of times (possibly zero).
After all operations are done, compute ∑_{i=1}^n a_i^2 — the sum of squares of all a_i. What is the largest sum of squares you can achieve?
Input
The first line contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5).
The second line contains n integers a_1, …, a_n (0 ≤ a_i < 2^{20}).
Output
Print a single integer — the largest possible sum of squares that can be achieved after several (possibly zero) operations.
Examples
Input
1
123
Output
15129
Input
3
1 3 5
Output
51
Input
2
349525 699050
Output
1099509530625
Note
In the first sample no operation can be made, thus the answer is 123^2.
In the second sample we can obtain the collection 1, 1, 7, and 1^2 + 1^2 + 7^2 = 51.
If x and y are represented in binary with equal number of bits (possibly with leading zeros), then each bit of x~AND~y is set to 1 if and only if both corresponding bits of x and y are set to 1. Similarly, each bit of x~OR~y is set to 1 if and only if at least one of the corresponding bits of x and y are set to 1. For example, x = 3 and y = 5 are represented as 011_2 and 101_2 (highest bit first). Then, x~AND~y = 001_2 = 1, and x~OR~y = 111_2 = 7. | instruction | 0 | 15,233 | 20 | 30,466 |
Tags: bitmasks, greedy, math
Correct Solution:
```
# -*- coding: utf-8 -*-
"""
@author: Saurav Sihag
"""
rr = lambda: input().strip()
# rri = lambda: int(rr())
rri = lambda: int(stdin.readline())
rrm = lambda: [int(x) for x in rr().split()]
# stdout.write(str()+'\n')
from sys import stdin, stdout
def sol():
n=rri()
v=rrm()
x=[0 for i in range(25)]
for i in v:
z=i
j=0
while z>0:
if (z&1)==1:
x[j]+=1
z=z>>1
j+=1
res=0
for i in range(n):
a=0
for j in range(25):
if x[j]>i:
z=1<<j
a+=z
res+=a*a
print(res)
return
sol()
# T = rri()
# for t in range(1, T + 1):
# ans = sol()
# print("Case #{}: {}".format(t, ans))
``` | output | 1 | 15,233 | 20 | 30,467 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gottfried learned about binary number representation. He then came up with this task and presented it to you.
You are given a collection of n non-negative integers a_1, …, a_n. You are allowed to perform the following operation: choose two distinct indices 1 ≤ i, j ≤ n. If before the operation a_i = x, a_j = y, then after the operation a_i = x~AND~y, a_j = x~OR~y, where AND and OR are bitwise AND and OR respectively (refer to the Notes section for formal description). The operation may be performed any number of times (possibly zero).
After all operations are done, compute ∑_{i=1}^n a_i^2 — the sum of squares of all a_i. What is the largest sum of squares you can achieve?
Input
The first line contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5).
The second line contains n integers a_1, …, a_n (0 ≤ a_i < 2^{20}).
Output
Print a single integer — the largest possible sum of squares that can be achieved after several (possibly zero) operations.
Examples
Input
1
123
Output
15129
Input
3
1 3 5
Output
51
Input
2
349525 699050
Output
1099509530625
Note
In the first sample no operation can be made, thus the answer is 123^2.
In the second sample we can obtain the collection 1, 1, 7, and 1^2 + 1^2 + 7^2 = 51.
If x and y are represented in binary with equal number of bits (possibly with leading zeros), then each bit of x~AND~y is set to 1 if and only if both corresponding bits of x and y are set to 1. Similarly, each bit of x~OR~y is set to 1 if and only if at least one of the corresponding bits of x and y are set to 1. For example, x = 3 and y = 5 are represented as 011_2 and 101_2 (highest bit first). Then, x~AND~y = 001_2 = 1, and x~OR~y = 111_2 = 7. | instruction | 0 | 15,234 | 20 | 30,468 |
Tags: bitmasks, greedy, math
Correct Solution:
```
n=int(input())
arr=[int(i) for i in input().split()]
binary=[]
num=[0 for i in range(21)]
for i in range(n):
b=bin(arr[i]).replace("0b","")
if len(b)<21:
for k in range(21-len(b)):
b='0'+b
binary.append(b)
for i in range(21):
for j in range(n):
if binary[j][i]=='1':
num[i]+=1
m=max(num)
f=0
ans=0
while(f<=m):
f+=1
a=''
for i in range(21):
if num[i]>0:
num[i]-=1
a=a+'1'
else:
a=a+'0'
ans=ans+(int(a,2))**2
print(ans)
``` | output | 1 | 15,234 | 20 | 30,469 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gottfried learned about binary number representation. He then came up with this task and presented it to you.
You are given a collection of n non-negative integers a_1, …, a_n. You are allowed to perform the following operation: choose two distinct indices 1 ≤ i, j ≤ n. If before the operation a_i = x, a_j = y, then after the operation a_i = x~AND~y, a_j = x~OR~y, where AND and OR are bitwise AND and OR respectively (refer to the Notes section for formal description). The operation may be performed any number of times (possibly zero).
After all operations are done, compute ∑_{i=1}^n a_i^2 — the sum of squares of all a_i. What is the largest sum of squares you can achieve?
Input
The first line contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5).
The second line contains n integers a_1, …, a_n (0 ≤ a_i < 2^{20}).
Output
Print a single integer — the largest possible sum of squares that can be achieved after several (possibly zero) operations.
Examples
Input
1
123
Output
15129
Input
3
1 3 5
Output
51
Input
2
349525 699050
Output
1099509530625
Note
In the first sample no operation can be made, thus the answer is 123^2.
In the second sample we can obtain the collection 1, 1, 7, and 1^2 + 1^2 + 7^2 = 51.
If x and y are represented in binary with equal number of bits (possibly with leading zeros), then each bit of x~AND~y is set to 1 if and only if both corresponding bits of x and y are set to 1. Similarly, each bit of x~OR~y is set to 1 if and only if at least one of the corresponding bits of x and y are set to 1. For example, x = 3 and y = 5 are represented as 011_2 and 101_2 (highest bit first). Then, x~AND~y = 001_2 = 1, and x~OR~y = 111_2 = 7. | instruction | 0 | 15,235 | 20 | 30,470 |
Tags: bitmasks, greedy, math
Correct Solution:
```
n = int(input())
A = list(map(int,input().split()))
bits = [0 for i in range(21)]
for i in range(n):
x = A[i]
for j in range(20):
if(x&(1<<j)):
bits[j]+=1
ans = 0
while(True):
flag = 0
num=0
for i in range(20):
if(bits[i]!=0):
flag=1
bits[i]-=1
num+=2**i
ans+=num*num
if(flag ==0):
break
print(ans)
``` | output | 1 | 15,235 | 20 | 30,471 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gottfried learned about binary number representation. He then came up with this task and presented it to you.
You are given a collection of n non-negative integers a_1, …, a_n. You are allowed to perform the following operation: choose two distinct indices 1 ≤ i, j ≤ n. If before the operation a_i = x, a_j = y, then after the operation a_i = x~AND~y, a_j = x~OR~y, where AND and OR are bitwise AND and OR respectively (refer to the Notes section for formal description). The operation may be performed any number of times (possibly zero).
After all operations are done, compute ∑_{i=1}^n a_i^2 — the sum of squares of all a_i. What is the largest sum of squares you can achieve?
Input
The first line contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5).
The second line contains n integers a_1, …, a_n (0 ≤ a_i < 2^{20}).
Output
Print a single integer — the largest possible sum of squares that can be achieved after several (possibly zero) operations.
Examples
Input
1
123
Output
15129
Input
3
1 3 5
Output
51
Input
2
349525 699050
Output
1099509530625
Note
In the first sample no operation can be made, thus the answer is 123^2.
In the second sample we can obtain the collection 1, 1, 7, and 1^2 + 1^2 + 7^2 = 51.
If x and y are represented in binary with equal number of bits (possibly with leading zeros), then each bit of x~AND~y is set to 1 if and only if both corresponding bits of x and y are set to 1. Similarly, each bit of x~OR~y is set to 1 if and only if at least one of the corresponding bits of x and y are set to 1. For example, x = 3 and y = 5 are represented as 011_2 and 101_2 (highest bit first). Then, x~AND~y = 001_2 = 1, and x~OR~y = 111_2 = 7. | instruction | 0 | 15,236 | 20 | 30,472 |
Tags: bitmasks, greedy, math
Correct Solution:
```
BITS = 32
n = int(input())
a = list(map(int, input().split()))
bits = [0 for i in range(BITS)]
for x in a:
for i in range(BITS):
if x % 2 == 1:
bits[i] += 1
x //= 2
M = max(bits)
ret = 0
while M > 0:
b = 0
for i in range(BITS):
if bits[i] > 0:
b += 2 ** i
bits[i] -= 1
M -= 1
ret += b * b
print(ret)
``` | output | 1 | 15,236 | 20 | 30,473 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gottfried learned about binary number representation. He then came up with this task and presented it to you.
You are given a collection of n non-negative integers a_1, …, a_n. You are allowed to perform the following operation: choose two distinct indices 1 ≤ i, j ≤ n. If before the operation a_i = x, a_j = y, then after the operation a_i = x~AND~y, a_j = x~OR~y, where AND and OR are bitwise AND and OR respectively (refer to the Notes section for formal description). The operation may be performed any number of times (possibly zero).
After all operations are done, compute ∑_{i=1}^n a_i^2 — the sum of squares of all a_i. What is the largest sum of squares you can achieve?
Input
The first line contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5).
The second line contains n integers a_1, …, a_n (0 ≤ a_i < 2^{20}).
Output
Print a single integer — the largest possible sum of squares that can be achieved after several (possibly zero) operations.
Examples
Input
1
123
Output
15129
Input
3
1 3 5
Output
51
Input
2
349525 699050
Output
1099509530625
Note
In the first sample no operation can be made, thus the answer is 123^2.
In the second sample we can obtain the collection 1, 1, 7, and 1^2 + 1^2 + 7^2 = 51.
If x and y are represented in binary with equal number of bits (possibly with leading zeros), then each bit of x~AND~y is set to 1 if and only if both corresponding bits of x and y are set to 1. Similarly, each bit of x~OR~y is set to 1 if and only if at least one of the corresponding bits of x and y are set to 1. For example, x = 3 and y = 5 are represented as 011_2 and 101_2 (highest bit first). Then, x~AND~y = 001_2 = 1, and x~OR~y = 111_2 = 7. | instruction | 0 | 15,237 | 20 | 30,474 |
Tags: bitmasks, greedy, math
Correct Solution:
```
import sys
input = sys.stdin.buffer.readline
n = int(input())
a = list(map(int, input().split()))
cnt = [0] * 20
for i, num in enumerate(a):
for j in range(20):
if num & (1 << j):
cnt[j] += 1
ans = 0
for i in range(n):
tmp = 0
for j in range(20):
if cnt[j] > 0:
tmp += (1 << j)
cnt[j] -= 1
ans += tmp ** 2
print(ans)
``` | output | 1 | 15,237 | 20 | 30,475 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Input
The input contains two integers N, M (1 ≤ N ≤ 1024, 2 ≤ M ≤ 16), separated by a single space.
Output
Output "YES" or "NO".
Examples
Input
2 3
Output
YES
Input
3 2
Output
NO
Input
33 16
Output
YES
Input
26 5
Output
NO | instruction | 0 | 15,307 | 20 | 30,614 |
Tags: *special, number theory
Correct Solution:
```
def xeno(n,m):
ans=[]
while(n):
ans.append(n%m)
n=int(n/m)
s=set()
for item in ans:
s.add(item)
# print(s)
# print(ans)
if len(s)==len(ans):
return 'YES'
else:
return 'NO'
if __name__=='__main__':
n=input().split(' ')
print(xeno(int(n[0]),int(n[1])))
``` | output | 1 | 15,307 | 20 | 30,615 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Input
The input contains two integers N, M (1 ≤ N ≤ 1024, 2 ≤ M ≤ 16), separated by a single space.
Output
Output "YES" or "NO".
Examples
Input
2 3
Output
YES
Input
3 2
Output
NO
Input
33 16
Output
YES
Input
26 5
Output
NO | instruction | 0 | 15,310 | 20 | 30,620 |
Tags: *special, number theory
Correct Solution:
```
def numberToBase(n, b):
if n == 0:
return [0]
digits = []
while n:
digits.append(int(n % b))
n //= b
return digits[::-1]
N, B = map(int, input().split())
D = numberToBase(N, B)
count = set()
correct = "YES"
for elt in D:
if not elt in count:
count.add(elt)
else:
correct = "NO"
break
print(correct)
``` | output | 1 | 15,310 | 20 | 30,621 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Prof. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.
Input
The first line of the input contains integer n (1 ≤ n < 1015).
Output
Print expected minimal number of digits 1.
Examples
Input
121
Output
6 | instruction | 0 | 15,427 | 20 | 30,854 |
Tags: brute force, dfs and similar, divide and conquer
Correct Solution:
```
multiplos_de_onze = [0, 1, 11, 111, 1111, 11111, 111111, 1111111, 11111111, 111111111, 1111111111, 11111111111,
111111111111, 1111111111111, 11111111111111, 111111111111111, 1111111111111111,
11111111111111111]
def procura_onze(n, i): # i = 16 pois será as posições do vetor decrementadas
divisao = int(n / multiplos_de_onze[i])
resto = n % multiplos_de_onze[i]
if resto == 0:
return divisao*i
else:
return divisao*i + min(i + procura_onze(multiplos_de_onze[i] - resto, i - 1), procura_onze(resto, i - 1))
def divide():
n = int(input())
m = procura_onze(n, 16)
print(m)
divide()
``` | output | 1 | 15,427 | 20 | 30,855 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Prof. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.
Input
The first line of the input contains integer n (1 ≤ n < 1015).
Output
Print expected minimal number of digits 1.
Examples
Input
121
Output
6 | instruction | 0 | 15,428 | 20 | 30,856 |
Tags: brute force, dfs and similar, divide and conquer
Correct Solution:
```
n = int(input())
d = {n: 0}
m = len(str(n)) + 1
u = int('1' * (m+1))
for i in range(m, 0, -1):
d, e, u = {}, d, u // 10
for v, c in e.items():
lim = v // u
for x in range(-1 - lim, 1 - lim):
t = v + x * u
d[t] = min(c + i * abs(x), d.get(t, 999))
print(d[0])
``` | output | 1 | 15,428 | 20 | 30,857 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Prof. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.
Input
The first line of the input contains integer n (1 ≤ n < 1015).
Output
Print expected minimal number of digits 1.
Examples
Input
121
Output
6 | instruction | 0 | 15,429 | 20 | 30,858 |
Tags: brute force, dfs and similar, divide and conquer
Correct Solution:
```
one = []
for i in range(17):
one.append(0)
def code():
i = 1
j = 0
k = 0
one[0] = 0
for i in range(1, 17):
one[i] = one[i-1]*10+1
n = int(input())
print(df(n, 16))
def df(n, i):
k = int(n/one[i])
n %= one[i]
if n == 0:
return k*i
else:
return k*i+min(i+df(one[i]-n, i-1), df(n, i-1))
code()
``` | output | 1 | 15,429 | 20 | 30,859 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Prof. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.
Input
The first line of the input contains integer n (1 ≤ n < 1015).
Output
Print expected minimal number of digits 1.
Examples
Input
121
Output
6 | instruction | 0 | 15,430 | 20 | 30,860 |
Tags: brute force, dfs and similar, divide and conquer
Correct Solution:
```
import math
acc = []
n = int(input())
def OneNum (num, One):
onetrans = num // acc[One]
num = num % acc[One]
if num == 0:
return onetrans*One
else:
return onetrans*One + min(OneNum(num, One-1), One + OneNum(acc[One] - num, One - 1))
acc.append(0)
for i in range(1,17):
acc.append (acc[i-1]*10 + 1)
print (OneNum(n,16))
``` | output | 1 | 15,430 | 20 | 30,861 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Prof. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.
Input
The first line of the input contains integer n (1 ≤ n < 1015).
Output
Print expected minimal number of digits 1.
Examples
Input
121
Output
6 | instruction | 0 | 15,431 | 20 | 30,862 |
Tags: brute force, dfs and similar, divide and conquer
Correct Solution:
```
n = int(input())
d = {n: 0}
u = 10 ** (len(str(n)) + 2) // 9
for i in range(len(str(n)) + 1, 0, -1):
d, e = {}, d
u //= 10
for v, c in e.items():
lim = v//u
for x in range(-1 - lim, 1 - lim):
t = v + x * u
d[t] = min(c + i * abs(x), d.get(t, 999))
print(d[0])
``` | output | 1 | 15,431 | 20 | 30,863 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Prof. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.
Input
The first line of the input contains integer n (1 ≤ n < 1015).
Output
Print expected minimal number of digits 1.
Examples
Input
121
Output
6 | instruction | 0 | 15,432 | 20 | 30,864 |
Tags: brute force, dfs and similar, divide and conquer
Correct Solution:
```
class OneArithmetic():
def __init__(self, n):
self.n = n
self.m = [0]*17
v = 0
for i in range(1,17):
v = 10*v+1
self.m[i] = v
def dfs(self, v, d):
v = abs(v)
if d == 1:
return v
elif v == 0:
return 0
else:
k = int(v/self.m[d])
ans = min( self.dfs( v - k * self.m[d] , d - 1 ) + k * d , self.dfs( ( k + 1 ) * self.m[d] - v , d - 1 ) + ( k + 1 ) * d )
return ans
def min_digits(self):
v = self.dfs(self.n,16)
return v
n = int(input())
print(OneArithmetic(n).min_digits())
``` | output | 1 | 15,432 | 20 | 30,865 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Prof. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.
Input
The first line of the input contains integer n (1 ≤ n < 1015).
Output
Print expected minimal number of digits 1.
Examples
Input
121
Output
6 | instruction | 0 | 15,433 | 20 | 30,866 |
Tags: brute force, dfs and similar, divide and conquer
Correct Solution:
```
n = int(input())
d = {n: 0}
u = 10 ** (len(str(n)) + 2) // 9
for i in range(len(str(n)) + 1, 0, -1):
d, e = {}, d
u //= 10
for v, c in e.items():
lim = v//u
for x in range(-1 - lim, 1 - lim):
t = v + x * u
d[t] = min(c + i * abs(x), d.get(t, 999))
print(d[0])
# Made By Mostafa_Khaled
``` | output | 1 | 15,433 | 20 | 30,867 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Prof. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.
Input
The first line of the input contains integer n (1 ≤ n < 1015).
Output
Print expected minimal number of digits 1.
Examples
Input
121
Output
6 | instruction | 0 | 15,434 | 20 | 30,868 |
Tags: brute force, dfs and similar, divide and conquer
Correct Solution:
```
n = int(input())
d = {}
def count(x):
if x == 0:
return 0
elif x in d:
return d[x]
x_s = str(x)
low = int("1"*len(x_s)) if int("1"*len(x_s)) <= x else int("1"*(len(x_s)-1))
high = int("1"*len(x_s)) if int("1"*len(x_s)) >= x else int("1"*(len(x_s)+1))
l_val, h_val = -1, -1
if abs(x - low) < x:
l_val = len(str(low)) + count(abs(x - low))
if abs(x - high) < x:
h_val = len(str(high)) + count(abs(x - high))
ret = min(l_val, h_val) if min(l_val, h_val) >= 0 else max(l_val, h_val)
d[x] = ret
return ret
print(count(n))
``` | output | 1 | 15,434 | 20 | 30,869 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Prof. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.
Input
The first line of the input contains integer n (1 ≤ n < 1015).
Output
Print expected minimal number of digits 1.
Examples
Input
121
Output
6
Submitted Solution:
```
multiplos_de_onze = [0, 1, 11, 111, 1111, 11111, 111111, 1111111, 11111111, 111111111, 1111111111, 11111111111,
111111111111, 1111111111111, 11111111111111, 111111111111111, 1111111111111111,
11111111111111111]
# Entrada maxima, n maior que 1 e n menor que 10 elevado a 15
def procura_onze(n, i): # i = 16 - pois será a ultima posição do vetor
divisao = int(n / multiplos_de_onze[i])
resto = n % multiplos_de_onze[i]
if resto == 0:
return divisao*i
else:
return divisao*i + min(i + procura_onze(multiplos_de_onze[i] - resto, i - 1), procura_onze(resto, i - 1))
def divide():
n = int(input())
m = procura_onze(n, 16)
print(m)
divide()
``` | instruction | 0 | 15,435 | 20 | 30,870 |
Yes | output | 1 | 15,435 | 20 | 30,871 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Prof. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.
Input
The first line of the input contains integer n (1 ≤ n < 1015).
Output
Print expected minimal number of digits 1.
Examples
Input
121
Output
6
Submitted Solution:
```
"""
Codeforces Testing Round 10 Problem C
Author : chaotic_iak
Language: Python 3.3.4
"""
def read(mode=2):
# 0: String
# 1: List of strings
# 2: List of integers
inputs = input().strip()
if mode == 0:
return inputs
if mode == 1:
return inputs.split()
if mode == 2:
return [int(x) for x in inputs.split()]
def write(s="\n"):
if isinstance(s, list): s = " ".join(s)
s = str(s)
print(s, end="")
################################################### SOLUTION
def g(n):
return (10**n-1)//9
def solve(n):
if n <= 6: return n
if 7 <= n <= 11: return 13-n
l = 1
while g(l) < n: l += 1
l -= 1
gl = g(l)
a = n
res1 = 0
res1 += (a // gl) * l
a %= gl
res1 += solve(a)
b = g(l+1) - n
res2 = l+1
res2 += (b // gl) * l
b %= gl
res2 += solve(b)
return min(res1, res2)
n, = read()
print(solve(n))
``` | instruction | 0 | 15,436 | 20 | 30,872 |
Yes | output | 1 | 15,436 | 20 | 30,873 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Prof. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.
Input
The first line of the input contains integer n (1 ≤ n < 1015).
Output
Print expected minimal number of digits 1.
Examples
Input
121
Output
6
Submitted Solution:
```
ans=1000000000000
mul = []
def dfs(now, num, opt):
if num == 0:
global ans
ans = min(ans, opt)
return
if now == -1:
return
i=-10
while i * mul[now] <= num:
i+=1
dfs(now-1, num-(i-1)*mul[now], opt+abs(i-1)*(now+1))
dfs(now-1, num-i*mul[now], opt+abs(i)*(now+1))
def main():
mul.append(int(1))
num = int(input())
for i in range(1,18,1):
mul.append(mul[i-1]*10)
for i in range(1,18,1):
mul[i] += mul[i-1]
i = 1
while mul[i] <= num:
i+=1
n=i
dfs(n, num, 0)
print(ans)
main()
``` | instruction | 0 | 15,437 | 20 | 30,874 |
Yes | output | 1 | 15,437 | 20 | 30,875 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Prof. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.
Input
The first line of the input contains integer n (1 ≤ n < 1015).
Output
Print expected minimal number of digits 1.
Examples
Input
121
Output
6
Submitted Solution:
```
import math
def find(n,i):
ans = 0
k = n // ones[i]
n = n % ones[i]
ans = ans + k * i
if n == 0:
return ans
return ans + min(find(n, i-1), i + find(ones[i] - n, i-1))
n = int(input())
ones = [0]
for i in range(1,17):
one = 10 * ones[i-1] + 1
ones.append(one)
print(find(n,16))
``` | instruction | 0 | 15,438 | 20 | 30,876 |
Yes | output | 1 | 15,438 | 20 | 30,877 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Prof. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.
Input
The first line of the input contains integer n (1 ≤ n < 1015).
Output
Print expected minimal number of digits 1.
Examples
Input
121
Output
6
Submitted Solution:
```
num=int(input())
kolvoed=0
while num:
sk='1'
while int(sk)<=num:
sk=sk+'1'
if num==6:
kolvoed+=6
num-=6
elif (int(sk)-num)>(num-int(sk[:-1])):
num=num-int(sk[:-1])
kolvoed+=len(sk)-1
else:
num=int(sk)-num
kolvoed+=len(sk)
print(kolvoed)
``` | instruction | 0 | 15,439 | 20 | 30,878 |
No | output | 1 | 15,439 | 20 | 30,879 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Prof. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.
Input
The first line of the input contains integer n (1 ≤ n < 1015).
Output
Print expected minimal number of digits 1.
Examples
Input
121
Output
6
Submitted Solution:
```
s = str(input())
ans = 0
while int(s)!=0:
l = len(s)
tmp = "1"*len(s) #xâu 1
so1 = int(s)
so2 = int(tmp)
#print("so1 =",so1)
#print("so2 =",so2)
#print("l =",l)
if so1 > so2*int(s[0]):
ans += int(s[0])*l
so1 = so1-so2*int(s[0])
s = str(so1)
#print("1",ans)
#print (s)
elif so1 < so2*int(s[0]):
ans+=l*int(s[0])
so1=so2*int(s[0])-so1
s = str(so1)
#print (s)
#print("2",ans)
else:
ans+=l*int(s[0])
s = str(so1-so2*int(s[0]))
#print("3",ans)
print(ans)
``` | instruction | 0 | 15,440 | 20 | 30,880 |
No | output | 1 | 15,440 | 20 | 30,881 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Prof. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.
Input
The first line of the input contains integer n (1 ≤ n < 1015).
Output
Print expected minimal number of digits 1.
Examples
Input
121
Output
6
Submitted Solution:
```
from sys import stdin, setrecursionlimit, stdout
#setrecursionlimit(1000000) #use "python" instead of "pypy" to avoid MLE
from collections import deque
from math import sqrt, floor, ceil, log, log2, log10, pi, gcd, sin, cos, asin
from heapq import heapify, heappop, heappush, heapreplace, heappushpop
from bisect import bisect_right, bisect_left
def ii(): return int(stdin.readline())
def fi(): return float(stdin.readline())
def mi(): return map(int, stdin.readline().split())
def fmi(): return map(float, stdin.readline().split())
def li(): return list(mi())
def si(): return stdin.readline().rstrip()
def lsi(): return list(si())
mod=1000000007
res=['NO', 'YES']
#######################################################################################
########################### M Y F U N C T I O N S ###########################
#######################################################################################
def ones(n):
global cnt
x=0
while True:
p=x*10+1
if abs(n-x)>abs(n-p):
x=p
cnt+=1
else:
return x
#######################################################################################
########################### M A I N P R O G R A M ###########################
#######################################################################################
test=1
test_case=1
while test<=test_case:
test+=1
x=ii()
cnt=0
while x:
x=abs(x-ones(x))
print(cnt)
``` | instruction | 0 | 15,441 | 20 | 30,882 |
No | output | 1 | 15,441 | 20 | 30,883 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Prof. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.
Input
The first line of the input contains integer n (1 ≤ n < 1015).
Output
Print expected minimal number of digits 1.
Examples
Input
121
Output
6
Submitted Solution:
```
n = int(input())
d = {n: 0}
u = 10 ** (len(str(n)) + 2) // 9
for i in range(len(str(n)) + 1, 0, -1):
print(d)
d, e = {}, d
u //= 10
for v, c in e.items():
lim = v//u
print(lim)
for x in range(-1 - lim, 1 - lim):
t = v + x * u
d[t] = min(c + i * abs(x), d.get(t, 999))
print(d[0])
``` | instruction | 0 | 15,442 | 20 | 30,884 |
No | output | 1 | 15,442 | 20 | 30,885 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A positive integer number n is written on a blackboard. It consists of not more than 105 digits. You have to transform it into a beautiful number by erasing some of the digits, and you want to erase as few digits as possible.
The number is called beautiful if it consists of at least one digit, doesn't have leading zeroes and is a multiple of 3. For example, 0, 99, 10110 are beautiful numbers, and 00, 03, 122 are not.
Write a program which for the given n will find a beautiful number such that n can be transformed into this number by erasing as few digits as possible. You can erase an arbitraty set of digits. For example, they don't have to go one after another in the number n.
If it's impossible to obtain a beautiful number, print -1. If there are multiple answers, print any of them.
Input
The first line of input contains n — a positive integer number without leading zeroes (1 ≤ n < 10100000).
Output
Print one number — any beautiful number obtained by erasing as few as possible digits. If there is no answer, print - 1.
Examples
Input
1033
Output
33
Input
10
Output
0
Input
11
Output
-1
Note
In the first example it is enough to erase only the first digit to obtain a multiple of 3. But if we erase the first digit, then we obtain a number with a leading zero. So the minimum number of digits to be erased is two. | instruction | 0 | 15,598 | 20 | 31,196 |
Tags: dp, greedy, math, number theory
Correct Solution:
```
def erase(s, n, m):
p = '147' if n == 1 else '258'
if sum(s.count(c) for c in p) < m:
return []
t = list(reversed(s))
for c in p:
while t.count(c) > 0 and m > 0:
t.remove(c)
m -= 1
while len(t) > 1 and t[-1] == '0':
t.pop()
return list(reversed(t))
def solve(s):
n = sum(int(c) for c in s) % 3
if n == 0:
a = b = s
if n == 1:
a = erase(s, 1, 1)
b = erase(s, 2, 2)
if n == 2:
a = erase(s, 2, 1)
b = erase(s, 1, 2)
s = max(a, b, key=len)
return '-1' if s == [] else s
def divide_by_three(s):
return solve(s)
if __name__ == "__main__":
s = list(input())
result = divide_by_three(s)
print(*result, sep='')
``` | output | 1 | 15,598 | 20 | 31,197 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A positive integer number n is written on a blackboard. It consists of not more than 105 digits. You have to transform it into a beautiful number by erasing some of the digits, and you want to erase as few digits as possible.
The number is called beautiful if it consists of at least one digit, doesn't have leading zeroes and is a multiple of 3. For example, 0, 99, 10110 are beautiful numbers, and 00, 03, 122 are not.
Write a program which for the given n will find a beautiful number such that n can be transformed into this number by erasing as few digits as possible. You can erase an arbitraty set of digits. For example, they don't have to go one after another in the number n.
If it's impossible to obtain a beautiful number, print -1. If there are multiple answers, print any of them.
Input
The first line of input contains n — a positive integer number without leading zeroes (1 ≤ n < 10100000).
Output
Print one number — any beautiful number obtained by erasing as few as possible digits. If there is no answer, print - 1.
Examples
Input
1033
Output
33
Input
10
Output
0
Input
11
Output
-1
Note
In the first example it is enough to erase only the first digit to obtain a multiple of 3. But if we erase the first digit, then we obtain a number with a leading zero. So the minimum number of digits to be erased is two. | instruction | 0 | 15,599 | 20 | 31,198 |
Tags: dp, greedy, math, number theory
Correct Solution:
```
n = list(input())
leng = 0
mp=[0,0,0]
for x in n:
leng += 1
mp[int(x)%3]+=1
tot = (mp[1]+2*mp[2])%3
if tot == 0:
print("".join(n))
exit()
if mp[tot] == 0:
do = tot ^ 3
cnt = 2
else:
if mp[tot] == 1 and int(n[0])%3==tot and n[1:3] == ['0','0']:
do =tot^3
cnt = 2
if mp[do] == 0:
do = tot
cnt = 1
else:
do = tot
cnt =1
index = leng-1
if cnt>=leng:
print(-1)
exit()
for x in range(cnt):
while int(n[index])%3 != do:
index-=1
n[index] = ""
index -=1
index = 0
ans = "".join(n)
while ans[index] == '0' and index<leng-cnt-1:
index+=1
print(ans[index:])
``` | output | 1 | 15,599 | 20 | 31,199 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A positive integer number n is written on a blackboard. It consists of not more than 105 digits. You have to transform it into a beautiful number by erasing some of the digits, and you want to erase as few digits as possible.
The number is called beautiful if it consists of at least one digit, doesn't have leading zeroes and is a multiple of 3. For example, 0, 99, 10110 are beautiful numbers, and 00, 03, 122 are not.
Write a program which for the given n will find a beautiful number such that n can be transformed into this number by erasing as few digits as possible. You can erase an arbitraty set of digits. For example, they don't have to go one after another in the number n.
If it's impossible to obtain a beautiful number, print -1. If there are multiple answers, print any of them.
Input
The first line of input contains n — a positive integer number without leading zeroes (1 ≤ n < 10100000).
Output
Print one number — any beautiful number obtained by erasing as few as possible digits. If there is no answer, print - 1.
Examples
Input
1033
Output
33
Input
10
Output
0
Input
11
Output
-1
Note
In the first example it is enough to erase only the first digit to obtain a multiple of 3. But if we erase the first digit, then we obtain a number with a leading zero. So the minimum number of digits to be erased is two. | instruction | 0 | 15,600 | 20 | 31,200 |
Tags: dp, greedy, math, number theory
Correct Solution:
```
import sys
from itertools import compress
s = input()
n = len(s)
mod = [0]*n
for i, x in enumerate(map(int, s)):
mod[i] = x % 3
total_mod = sum(mod) % 3
def remove_zeros(a):
for i in range(n):
if not a[i]:
continue
if s[i] == '0':
a[i] = 0
else:
return
if total_mod == 0:
a = [1]*n
remove_zeros(a)
ans = ''.join(compress(s, a))
if ans:
print(ans)
else:
print(0 if '0' in s else -1)
else:
ans1, ans2 = '', ''
for i in range(n-1, -1, -1):
if mod[i] == total_mod:
a = [1]*n
a[i] = 0
remove_zeros(a)
ans1 = ''.join(compress(s, a))
break
rem = 2
a = [1]*n
for i in range(n-1, -1, -1):
if mod[i] == 3 - total_mod:
a[i] = 0
rem -= 1
if rem == 0:
remove_zeros(a)
ans2 = ''.join(compress(s, a))
break
ans = ans1 if len(ans1) > len(ans2) else ans2
if ans:
print(ans)
else:
print(0 if '0' in s else -1)
``` | output | 1 | 15,600 | 20 | 31,201 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A positive integer number n is written on a blackboard. It consists of not more than 105 digits. You have to transform it into a beautiful number by erasing some of the digits, and you want to erase as few digits as possible.
The number is called beautiful if it consists of at least one digit, doesn't have leading zeroes and is a multiple of 3. For example, 0, 99, 10110 are beautiful numbers, and 00, 03, 122 are not.
Write a program which for the given n will find a beautiful number such that n can be transformed into this number by erasing as few digits as possible. You can erase an arbitraty set of digits. For example, they don't have to go one after another in the number n.
If it's impossible to obtain a beautiful number, print -1. If there are multiple answers, print any of them.
Input
The first line of input contains n — a positive integer number without leading zeroes (1 ≤ n < 10100000).
Output
Print one number — any beautiful number obtained by erasing as few as possible digits. If there is no answer, print - 1.
Examples
Input
1033
Output
33
Input
10
Output
0
Input
11
Output
-1
Note
In the first example it is enough to erase only the first digit to obtain a multiple of 3. But if we erase the first digit, then we obtain a number with a leading zero. So the minimum number of digits to be erased is two. | instruction | 0 | 15,601 | 20 | 31,202 |
Tags: dp, greedy, math, number theory
Correct Solution:
```
n = input()
nums = [int(i)%3 for i in n]
ones = nums.count(1)
twos = nums.count(2)
dis = (ones-twos)%3
def solve():
global n
global nums
global dis
if dis==0:
return n
t = rfind(dis)
if t>0 or (t==0 and len(n)>1 and nums[t+1]!=0):
return n[:t]+n[t+1:]
g,c = findtwo(3-dis)
if g>0:
return n[:g]+n[g+1:c]+n[c+1:]
if nums[0]==dis:
return tr(n[1:])
return tr(n[:g]+n[g+1:c]+n[c+1:])
def rfind(t):
c=-1
for i in range(len(n)):
if nums[i]==t:
c=i
return c
def findtwo(tr):
c=-1
g=-1
for i in range(len(n)):
if nums[i]==tr:
c=g
g=i
return c,g
def tr(s):
if len(s)==0:
return '-1'
i = 0
while i<len(s)-1 and s[i]=='0': i+=1
return s[i:]
print(solve())
``` | output | 1 | 15,601 | 20 | 31,203 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A positive integer number n is written on a blackboard. It consists of not more than 105 digits. You have to transform it into a beautiful number by erasing some of the digits, and you want to erase as few digits as possible.
The number is called beautiful if it consists of at least one digit, doesn't have leading zeroes and is a multiple of 3. For example, 0, 99, 10110 are beautiful numbers, and 00, 03, 122 are not.
Write a program which for the given n will find a beautiful number such that n can be transformed into this number by erasing as few digits as possible. You can erase an arbitraty set of digits. For example, they don't have to go one after another in the number n.
If it's impossible to obtain a beautiful number, print -1. If there are multiple answers, print any of them.
Input
The first line of input contains n — a positive integer number without leading zeroes (1 ≤ n < 10100000).
Output
Print one number — any beautiful number obtained by erasing as few as possible digits. If there is no answer, print - 1.
Examples
Input
1033
Output
33
Input
10
Output
0
Input
11
Output
-1
Note
In the first example it is enough to erase only the first digit to obtain a multiple of 3. But if we erase the first digit, then we obtain a number with a leading zero. So the minimum number of digits to be erased is two. | instruction | 0 | 15,602 | 20 | 31,204 |
Tags: dp, greedy, math, number theory
Correct Solution:
```
s=input()
rem=0
rems=[0]*(len(s))
one=[]
two=[]
for i in range(len(s)):
rems[i]=int(s[i])%3
if rems[i]==1:
one.append(i)
elif rems[i]==2:
two.append(i)
rem+=int(s[i])
rem%=3
include=[1]*(len(s))
include1=[1]*(len(s))
f=0
if rem==1:
if len(one):
include[one[len(one)-1]]=0
if len(two)>=2:
include1[two[len(two)-1]]=0
include1[two[len(two) - 2]] = 0
elif rem==2:
one, two=two, one
if len(one):
include[one[len(one)-1]]=0
if len(two)>=2:
include1[two[len(two)-1]]=0
include1[two[len(two) - 2]] = 0
ans=[]
ans1=[]
#print(include)
for i in range(len(s)):
if include[i]:
ans.append(int(s[i]))
if include1[i]:
ans1.append(int(s[i]))
fans = []
fans1 = []
for i in ans:
if f == 0 and i == 0:
continue
if i:
f = 1
fans.append(i)
elif f:
fans.append(i)
ans.sort()
if len(ans):
if ans[0] == ans[len(ans) - 1] == 0:
fans.append(0)
f=0
for i in ans1:
if f == 0 and i == 0:
continue
if i:
f = 1
fans1.append(i)
elif f:
fans1.append(i)
ans1.sort()
if len(ans1):
if ans1[0] == ans1[len(ans1) - 1] == 0:
fans1.append(0)
f=0
#print(ans)
#print(fans1, fans)
if (len(fans)==0 or sum(fans)%3) and (len(fans1)==0 or sum(fans1)%3):
print(-1)
else:
if len(fans)<len(fans1):
fans, fans1=fans1, fans
if sum(fans)%3==0:
for i in fans:
print(i,end='')
else:
for i in fans1:
print(i,end='')
``` | output | 1 | 15,602 | 20 | 31,205 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A positive integer number n is written on a blackboard. It consists of not more than 105 digits. You have to transform it into a beautiful number by erasing some of the digits, and you want to erase as few digits as possible.
The number is called beautiful if it consists of at least one digit, doesn't have leading zeroes and is a multiple of 3. For example, 0, 99, 10110 are beautiful numbers, and 00, 03, 122 are not.
Write a program which for the given n will find a beautiful number such that n can be transformed into this number by erasing as few digits as possible. You can erase an arbitraty set of digits. For example, they don't have to go one after another in the number n.
If it's impossible to obtain a beautiful number, print -1. If there are multiple answers, print any of them.
Input
The first line of input contains n — a positive integer number without leading zeroes (1 ≤ n < 10100000).
Output
Print one number — any beautiful number obtained by erasing as few as possible digits. If there is no answer, print - 1.
Examples
Input
1033
Output
33
Input
10
Output
0
Input
11
Output
-1
Note
In the first example it is enough to erase only the first digit to obtain a multiple of 3. But if we erase the first digit, then we obtain a number with a leading zero. So the minimum number of digits to be erased is two. | instruction | 0 | 15,603 | 20 | 31,206 |
Tags: dp, greedy, math, number theory
Correct Solution:
```
import bisect
from itertools import accumulate
import os
import sys
import math
from decimal import *
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
def input(): return sys.stdin.readline().rstrip("\r\n")
def isPrime(n) :
if (n <= 1) : return False
if (n <= 3) : return True
if (n % 2 == 0 or n % 3 == 0) : return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
def SieveOfEratosthenes(n):
prime=[]
primes = [True for i in range(n+1)]
p = 2
while (p * p <= n):
if (primes[p] == True):
prime.append(p)
for i in range(p * p, n+1, p):
primes[i] = False
p += 1
return prime
def primefactors(n):
fac=[]
while(n%2==0):
fac.append(2)
n=n//2
for i in range(3,int(math.sqrt(n))+2):
while(n%i==0):
fac.append(i)
n=n//i
if n>1:
fac.append(n)
return fac
def factors(n):
fac=set()
fac.add(1)
fac.add(n)
for i in range(2,int(math.sqrt(n))+1):
if n%i==0:
fac.add(i)
fac.add(n//i)
return list(fac)
def modInverse(a, m):
m0 = m
y = 0
x = 1
if (m == 1):
return 0
while (a > 1):
q = a // m
t = m
m = a % m
a = t
t = y
y = x - q * y
x = t
if (x < 0):
x = x + m0
return x
#------------------------------------------------------code by AD18/apurva3455
def deleteD(n,num):
rel=list(reversed(s))
for digit in reversed(s):
if int(digit)%3==n :
rel.remove(digit)
num-=1
if num==0 :
if len(rel)==0:
return []
while rel[-1]=='0' and len(rel)>1:
rel.pop()
return list(reversed(rel))
return []
s=input()
n=sum([int(c) for c in s])%3
if n==0:
print(s)
else:
if n==1:
a=deleteD(1, 1)
b=deleteD(2, 2)
else:
a=deleteD(1, 2)
b=deleteD(2, 1)
s=max(a, b, key=len)
if len(s):
print(''.join(s))
else:
print(-1)
``` | output | 1 | 15,603 | 20 | 31,207 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A positive integer number n is written on a blackboard. It consists of not more than 105 digits. You have to transform it into a beautiful number by erasing some of the digits, and you want to erase as few digits as possible.
The number is called beautiful if it consists of at least one digit, doesn't have leading zeroes and is a multiple of 3. For example, 0, 99, 10110 are beautiful numbers, and 00, 03, 122 are not.
Write a program which for the given n will find a beautiful number such that n can be transformed into this number by erasing as few digits as possible. You can erase an arbitraty set of digits. For example, they don't have to go one after another in the number n.
If it's impossible to obtain a beautiful number, print -1. If there are multiple answers, print any of them.
Input
The first line of input contains n — a positive integer number without leading zeroes (1 ≤ n < 10100000).
Output
Print one number — any beautiful number obtained by erasing as few as possible digits. If there is no answer, print - 1.
Examples
Input
1033
Output
33
Input
10
Output
0
Input
11
Output
-1
Note
In the first example it is enough to erase only the first digit to obtain a multiple of 3. But if we erase the first digit, then we obtain a number with a leading zero. So the minimum number of digits to be erased is two. | instruction | 0 | 15,604 | 20 | 31,208 |
Tags: dp, greedy, math, number theory
Correct Solution:
```
n = input()
if len(n) < 3:
if len(n) == 1:
if int(n) % 3 != 0:
print(-1)
else:
print(n)
if len(n) == 2:
if (int(n[0]) + int(n[1])) % 3 == 0:
print(n)
elif int(n[0]) % 3 == 0:
print(n[0])
elif int(n[1]) % 3 == 0:
print(n[1])
else:
print(-1)
else:
for i in range(len(n)):
if n[i] != '0':
n = n[i:]
break
if n[0] == '0':
n = '0'
dig_sum = sum([int(x) for x in n]) % 3
found = dig_sum == 0
result = "0"
if not found:
for i in range(len(n) - 1, -1, -1):
if (dig_sum - int(n[i])) % 3 == 0:
found = True
tmp = n[:i] + n[i + 1:]
break
if found:
for i in range(len(tmp)):
if tmp[i] != '0':
tmp = tmp[i:]
break
if tmp[0] == '0':
tmp = '0'
if found:
result = tmp
found_two = False
if len(n) > 2:
for i in range(len(n) - 1, -1, -1):
if int(n[i]) % 3 != 0:
dig_sum -= int(n[i])
tmp = n[:i] + n[i + 1:]
break
for i in range(len(tmp) - 1, -1, -1):
if (dig_sum - int(tmp[i])) % 3 == 0:
found_two = True
tmp = tmp[:i] + tmp[i + 1:]
break
if found_two:
for i in range(len(tmp)):
if tmp[i] != '0':
tmp = tmp[i:]
break
if tmp[0] == '0':
tmp = '0'
if not found:
result = tmp
elif found_two and len(result) < len(tmp):
result = tmp
else:
result = n
print(result)
``` | output | 1 | 15,604 | 20 | 31,209 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A positive integer number n is written on a blackboard. It consists of not more than 105 digits. You have to transform it into a beautiful number by erasing some of the digits, and you want to erase as few digits as possible.
The number is called beautiful if it consists of at least one digit, doesn't have leading zeroes and is a multiple of 3. For example, 0, 99, 10110 are beautiful numbers, and 00, 03, 122 are not.
Write a program which for the given n will find a beautiful number such that n can be transformed into this number by erasing as few digits as possible. You can erase an arbitraty set of digits. For example, they don't have to go one after another in the number n.
If it's impossible to obtain a beautiful number, print -1. If there are multiple answers, print any of them.
Input
The first line of input contains n — a positive integer number without leading zeroes (1 ≤ n < 10100000).
Output
Print one number — any beautiful number obtained by erasing as few as possible digits. If there is no answer, print - 1.
Examples
Input
1033
Output
33
Input
10
Output
0
Input
11
Output
-1
Note
In the first example it is enough to erase only the first digit to obtain a multiple of 3. But if we erase the first digit, then we obtain a number with a leading zero. So the minimum number of digits to be erased is two. | instruction | 0 | 15,605 | 20 | 31,210 |
Tags: dp, greedy, math, number theory
Correct Solution:
```
m=list(input())
n=list(map(int,m))
s=sum(n)
l=len(n)
if(s%3==0):
print("".join(m))
else:
r=s%3
for j in range(1,len(n)):
if(n[j]%3==r):
n.pop(j)
break
if(len(n)==l):
flag=0
if(n[0]%3==r):
if(len(n)>1):
if(n[1]!=0):
n.pop(0)
flag=1
if(flag==0):
num=[]
count=0
for j in range(1,len(n)):
if(n[j]%3!=0 and n[j]%3!=r):
count+=1
num.append(j)
if(count==2):
break
if(count==2):
n.pop(num[1])
n.pop(num[0])
elif(count==1):
n.pop(num[0])
n.pop(0)
else:
n.pop(0)
if(len(n)==0):
print(-1)
else:
j=0
flag=0
while(flag==0 and len(n)>1):
flag=1
if(n[j]==0):
n.pop(j)
flag=0
for j in range(len(n)):
print(n[j],end="")
print("")
``` | output | 1 | 15,605 | 20 | 31,211 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A positive integer number n is written on a blackboard. It consists of not more than 105 digits. You have to transform it into a beautiful number by erasing some of the digits, and you want to erase as few digits as possible.
The number is called beautiful if it consists of at least one digit, doesn't have leading zeroes and is a multiple of 3. For example, 0, 99, 10110 are beautiful numbers, and 00, 03, 122 are not.
Write a program which for the given n will find a beautiful number such that n can be transformed into this number by erasing as few digits as possible. You can erase an arbitraty set of digits. For example, they don't have to go one after another in the number n.
If it's impossible to obtain a beautiful number, print -1. If there are multiple answers, print any of them.
Input
The first line of input contains n — a positive integer number without leading zeroes (1 ≤ n < 10100000).
Output
Print one number — any beautiful number obtained by erasing as few as possible digits. If there is no answer, print - 1.
Examples
Input
1033
Output
33
Input
10
Output
0
Input
11
Output
-1
Note
In the first example it is enough to erase only the first digit to obtain a multiple of 3. But if we erase the first digit, then we obtain a number with a leading zero. So the minimum number of digits to be erased is two.
Submitted Solution:
```
def deleteD(n,num):
rel=list(reversed(s))
for digit in reversed(s):
if int(digit)%3==n :
rel.remove(digit)
num-=1
if num==0 :
if len(rel)==0:
return []
while rel[-1]=='0' and len(rel)>1:
rel.pop()
return list(reversed(rel))
return []
s=input()
n=sum([int(c) for c in s])%3
if n==0:
print(s)
else:
if n==1:
a=deleteD(1, 1)
b=deleteD(2, 2)
else:
a=deleteD(1, 2)
b=deleteD(2, 1)
s=max(a, b, key=len)
if len(s):
print(''.join(s))
else:
print(-1)
``` | instruction | 0 | 15,606 | 20 | 31,212 |
Yes | output | 1 | 15,606 | 20 | 31,213 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.