qyliang/CodeNanoFix huggingface dataset:
Pair of Primes

We arrange the numbers between 1 and N (1 <= N <= 10000) in increasing order and decreasing order. Two numbers facing each other form a pair. The task is to compute the number of pairs P such that both numbers in the pairs are prime.

Input

Input contains several test cases. Each test case consists of an integer N in one line.

Output

For each line of input, output P.

Sample Input
1
4
7
51

Output for the Sample Input
0
2
2
6

# Buggy version:
primes = [0, 0] + [1] * 9999
for i in range(2, 101):
    if primes[i]:
        for j in range(i*i, 10001, i):
            primes[j] = 0

while True:
    try:
        N = int(input())
    except:
        break
    print(sum(primes[i] & primes[-i] for i in range(1, N+1)))

# Fixed version:
primes = [0, 0] + [1] * 9999
for i in range(2, 101):
    if primes[i]:
        for j in range(i*i, 10001, i):
            primes[j] = 0

while True:
    try:
        N = int(input())
    except:
        break
    print(sum(primes[i] and primes[N-i+1] for i in range(1, N+1)))

# Buggy version:
import math

def ifprime(num):
  if num == 1:
    return False
  for i in range(2,math.floor(num ** 0.5) + 1):
    if num % i:
      continue
    else:
      return False
  return True

while(True):
  try:
    num = int(input())
  except:
    break
  if num % 2 == 0:
    print(0)
  else:
    count = 0
    for i in range(1,num+1):
      if ifprime(i) and ifprime(num+1-i):
        count += 1
    print(count)



# Fixed version:
import math

def ifprime(num):
  if num == 1:
    return False
  for i in range(2,math.floor(num ** 0.5) + 1):
    if num % i:
      continue
    else:
      return False
  return True

while(True):
  try:
    num = int(input())
  except:
    break
  count = 0
  for i in range(1,num+1):
    if ifprime(i) and ifprime(num+1-i):
      count += 1
  print(count)
Title: What Color Is The Universe?

On a clear night, a boy named Campanella gazed at the sky, observing stars of various colors. Lost in time, he pondered, "There are many stars in space. What color is the universe if I observe it from outside?" He proposed a hypothesis: "When I observe the stars, if more than half have the same color, that is the color of the universe."

Sick in bed, he sought help to develop a program to identify the color of the universe. Given an array A, find m such that Nm > (|A| / 2). If no such m exists, report "NO COLOR."

Input: For each test case, the first line contains |A|, followed by |A| integers. The input terminates with a line containing a single 0.

Output: For each test case, output m in a line. If there is no answer, output "NO COLOR."

Sample Input:
8
3 1 2 3 3 1 5 3
7
5 2 5 3 4 5 5
0

Output for the Sample Input:
NO COLOR
5

# Buggy version:
while True:
    num=int(input())
    if num==0:
        break
    stars=sorted(input().split())
    print(stars)
    if stars.count(stars[num//2]) > num/2 :
        print(stars[num//2])
    else:
        print("NO COLOR")

# Fixed version:
while True:
    num=int(input())
    if num==0:
        break
    stars=sorted(input().split())
    if stars.count(stars[num//2]) > num/2 :
        print(stars[num//2])
    else:
        print("NO COLOR")
Problem I: A Piece of Cake

In the city, there are two pastry shops. One shop was very popular because its cakes are pretty tasty. However, there was a man who is displeased at the shop. He was an owner of another shop. Although the cause of his shop's unpopularity is the incredibly awful taste of its cakes, he never improved it. He was just growing hate, ill, envy, and jealousy.

Finally, he decided to vandalize the rival.

His vandalize is to mess up sales record of cakes. The rival shop sells K kinds of cakes and sales quantity is recorded for each kind. He calculates the sum of sales quantities for all pairs of cakes. Getting K(K-1)/2 numbers, then he rearranges them randomly, and replaces the original sales record with them.

The owner of the rival shop is bothered. Could you write, at least, a program that finds the total sales quantity of all cakes for the pitiful owner?

Input

Input file contains several data sets. A single data set has the following format:

K
c1 c2 ... c(K*(K-1)/2)

K is an integer that denotes how many kinds of cakes are sold. ci is an integer that denotes a number written on the card.

The end of input is denoted by a case where K = 0. You should output nothing for this case.

Output

For each data set, output the total sales quantity in one line.

Constraints
- Judge data contains at most 100 data sets.
- 2 <= K <= 100
- 0 <= ci <= 100

Sample Input
2
2
3
5 4 3
0

Output for the Sample Input
2
6

# Buggy version:
while True:
    K = int(input())
    if K == 0:
        break
    else:
        po = [int(i) for i in input().split()]
        print(sum(po)/(K-1))

# Fixed version:
while True:
    K = int(input())
    if K == 0:
        break
    elif K == 1:
        print(int(input()))
    else:
        po = [int(i) for i in input().split()]
        print(int(sum(po)/(K-1)))

# Buggy version:
while 1:
  k=input()-1
  if k==0:break
  print sum(map(int, raw_input().split()))/k

# Fixed version:
while True:
  k = int(input())
  if k == 0:
    break

  print(sum(map(int, input().split())) // (k - 1))
Problem 01: Kyudo: A Japanese Art of Archery

Ito joined the archery club after entering high school. Initially struggling to hit the target, he eventually improved enough to reach it by the fall of his first year. One day, his senior, Kato, suggested, "Why not participate in a close-range archery competition?" Ito, eager for the challenge, agreed to compete in his first tournament.

In close-range archery, participants shoot four arrows in a round, recording the number of hits. This process is repeated multiple times, and the total number of hits is compared.

To help Ito prepare for the competition, Kato decided to create a program that calculates the total number of hits expected during the actual event. The program reads the total number of shots, "n," and the number of hits for each round, then outputs the total number of hits.

For instance, if the total number of shots, "n," is 20, and each round consists of 4 shots, the program will repeat this process 5 times, and the number of hits for each round will be input 5 times.

Input:
Multiple datasets are provided as input. For each dataset, the first line contains "n" (an integer that is a multiple of 4), followed by "n/4" integers representing the number of hits for each round.

The input ends when "n" is 0, and no output should be provided for this input.

Output:
For each dataset, output the total number of hits on a single line.

Sample Input:
20
4
3
2
1
3
8
2
0
0

Output for the Sample Input:
13
2

# Buggy version:
while True:
    n = input()
    if n == 0: break
    print ans(input() for i in range(n/4))

# Fixed version:
while True:
    n = int(input())
    if n==0: break
    ans = 0
    for i in range(n//4):
        ans += int(input())
    print(ans)

# Buggy version:
while True:
    n = int(input())
    if n == 0: break
    print(sum([int(input()) for _ in range(n//5)]))

# Fixed version:
while True:
  n = int(input())
  if n == 0:
    break
  print(sum([int(input()) for _ in range(n // 4)]))
Problem B: Old Bridges

Long long ago, there was a thief searching for treasures on various islands. He found n islands with treasures and one empty island. Most islands had a seashore, and he could only land on the empty island. Each island had an old bridge connecting it to the others. The thief aims to visit all islands, collecting treasures without the bridges breaking due to carrying too much. Write a program to determine if he can collect all treasures and return to the initial island by choosing a suitable visiting order.

Input:
Several datasets. Each dataset starts with an integer n. The next n lines contain information about the islands: the amount of treasures and the maximum amount he can carry when crossing the bridge to each island.

Output:
For each dataset, print "Yes" if he can collect all treasures and return, otherwise print "No".

Constraints:
1 ≤ n ≤ 25

Sample Input:
3
2 3
3 6
1 2
3
2 3
3 5
1 2
0

Sample Output:
Yes
No

# Buggy version:
while True:
    n = int(input())
    if n == 0:
        break
    z = sorted([tuple(map(int, input().split())) for _ in range(n)],  key=lambda x: x[1])
    cnt = total = 0
    for a, b in z:
        total += a
        if total > b:
            cnt = 1
            break
    print("Yes" if cnt else "No")

# Fixed version:
while True:
    n = int(input())
    if n == 0:
        break
    z = sorted([tuple(map(int, input().split())) for _ in range(n)],  key=lambda x: x[1])
    total = 0
    for a, b in z:
        total += a
        if total > b:
            print("No")
            break
    else:
        print("Yes")

# Buggy version:
def sky(x):
    return x[1]


while True:
    n = int(input())
    if n == 0:
        break
    
    arr = [[] for i in range(n)]
    sumh = 0
    for i in range(n):
        arr[i] = list(map(int, input().split()))
        sumh += arr[i][0]
    arr.sort(key=sky, reverse=True)
    print(arr)
    res = True
    for e in arr:
        if sumh > e[1]:
            res = False
            break
        sumh -= e[0]
    if res:
        print("Yes")
    else:
        print("No")



# Fixed version:
def sky(x):
    return x[1]


while True:
    n = int(input())
    if n == 0:
        break
    
    arr = [[] for i in range(n)]
    sumh = 0
    for i in range(n):
        arr[i] = list(map(int, input().split()))
    arr.sort(key=sky)
    res = True
    for e in arr:
        sumh += e[0]
        if sumh > e[1]:
            res = False
            break
    if res:
        print("Yes")
    else:
        print("No")
Takahashi wants to give his mother a string with the highest possible value. The value of a string T is the length of the longest common subsequence of T and its reverse, T'. Takahashi has a string S and can change at most K characters in S to obtain the highest possible value. Find the highest possible value achievable. Constraints: 1 ≤ |S| ≤ 300, 0 ≤ K ≤ |S|, S consists of lowercase English letters, and K is an integer. Input is given as S and K, and the output should be the highest possible value achievable. For example, if the input is "abcabcabc" and 1, the output should be 7. If the input is "atcodergrandcontest" and 3, the output should be 15.

# Buggy version:
def main():
    s = input()
    n = len(s)
    k = int(input())
    # dp[使った回数][左端からの距離][左端]
    dp = [[[1]*(n-i) for i in range(n)] for _ in range(k+1)]

    dp2 = dp[0][1]
    for i in range(n-1):
        if s[i] == s[i+1]:
            dp2[i] = 2
    if k > 0:
        for cnt in range(1, k+1):
            dp2 = dp[cnt][1]
            for i in range(n-1):
                dp2[i] = 2

    for cnt in range(k):
        dp2 = dp[cnt]
        for d in range(2, n):
            dp3 = dp2[d]
            for left in range(n-d):
                right = left+d
                plus = (s[left] == s[right])*2
                dp3[left] = max(
                    dp3[left], dp2[d-1][left],
                    dp2[d-1][left+1], dp2[d-2][left+1]+plus)
                dp[cnt+1][d][left] = max(
                    dp[cnt+1][d][left], dp3[left], dp2[d-2][left+1]+2)
    dp2 = dp[k]
    for d in range(2, n):
        dp3 = dp[d]
        for left in range(n-d):
            right = left+d
            plus = (s[left] == s[right])*2
            dp3[left] = max(
                dp3[left], dp2[d-1][left], dp2[d-1][left+1], dp2[d-2][left+1]+plus)
    print(dp[-1][-1][0])


main()

# Fixed version:
def main():
    s = input()
    n = len(s)
    k = int(input())
    # dp[使った回数][左端からの距離][左端]
    dp = [[[1]*(n-i) for i in range(n)] for _ in range(k+1)]

    for i in range(n-1):
        if s[i] == s[i+1]:
            dp[0][1][i] = 2
    if k > 0:
        for cnt in range(1, k+1):
            for i in range(n-1):
                dp[cnt][1][i] = 2

    for cnt in range(k):
        for d in range(2, n):
            for left in range(n-d):
                right = left+d
                plus = (s[left] == s[right])*2
                dp[cnt][d][left] = max(
                    dp[cnt][d][left], dp[cnt][d-1][left],
                    dp[cnt][d-1][left+1], dp[cnt][d-2][left+1]+plus)
                dp[cnt+1][d][left] = max(
                    dp[cnt+1][d][left], dp[cnt][d][left], dp[cnt][d-2][left+1]+2)
    for d in range(2, n):
        for left in range(n-d):
            right = left+d
            plus = (s[left] == s[right])*2
            dp[k][d][left] = max(
                dp[k][d][left], dp[k][d-1][left], dp[k][d-1][left+1], dp[k][d-2][left+1]+plus)
    print(dp[-1][-1][0])


main()
Title: 観音堂

In the backyard of Ichiro's house, there is a Kannon temple. To reach this temple, there are 30 steps from the base, and Ichiro visits the temple almost every day. Ichiro can climb 3 steps at a time. He realized that there are numerous ways to climb the stairs while playing. Wanting to try 10 types of climbs in a day, he needs help to calculate the time required to execute all climb types. The input consists of the number of steps, and the output should be the number of years required for Ichiro to execute all climb types. Each dataset ends with a single zero. The number of datasets does not exceed 30.

Sample Input:
1
10
20
25
0

Output for the Sample Input:
1
1
34
701

# Buggy version:
a = [1, 1, 2]
for i in range(3, 31):
    a.append(sum(a[-3:]))

while True:
    n = int(input())
    if not n:
        break
    print(((a[n] + 9) / 10 + 364) / 365)

# Fixed version:
a = [1]
for i in range(1, 31):
    a.append(sum(a[-3:]))

while True:
    n = int(input())
    if not n:
        break
    print(((a[n] + 9) // 10 + 364) // 365)

# Buggy version:
#coding:utf-8
from __future__ import division,print_function
try:
    input = raw_input
except NameError:
    pass
# 上記のコードはPython2とPython3の違いを一部吸収するためのもの
memo=[0]*31
def solve(x):
    if memo[x]==0:
        if x>1:
            memo[x]=solve(x-1)+solve(x-2)+solve(x-3)
            return memo[x]
        elif x==0:
            memo[x]=1
            return 1
        else:
            return 0
    else:
        return memo[x]

def main():
    while True:
        inp=int(input())
        if inp==0:
            break
        print(solve(inp))

main()

# Fixed version:
#coding:utf-8
from __future__ import division,print_function
try:
    input = raw_input
except NameError:
    pass
# 上記のコードはPython2とPython3の違いを一部吸収するためのもの
memo=[0]*31
def solve(x):
    if memo[x]==0:
        if x>0:
            memo[x]=solve(x-1)+solve(x-2)+solve(x-3)
            return memo[x]
        elif x==0:
            memo[x]=1
            return 1
        else:
            return 0
    else:
        return memo[x]

def main():
    while True:
        inp=int(input())
        if inp==0:
            break
        print((solve(inp)-1)//3650+1)

main()
Title: Blackjack

Blackjack is a card game played in casinos using cards numbered from 1 to 13. Each card has a specific point value as follows:
- 1 is worth either 1 or 11 points
- 2 to 9 are worth their face value
- 10 to 13 are worth 10 points

In this game, there are multiple participants, including a dealer, each holding a set of cards, referred to as a "hand." The hand's score is the sum of the card values, calculated as follows:
- If the total exceeds 21, the hand's score is 0
- For the value 1, it can be counted as 1 or 11, with the higher value chosen if it maximizes the hand's score

Create a program that takes the dealt card information as input and outputs the hand's score.

Input:
Multiple datasets are provided as input, ending with a single line containing only 0. Each dataset is in the following format:
c1 c2 ... cn
Where each ci (1 ≤ ci ≤ 13) represents the integer written on the ith card, separated by a space. The number of cards, n, does not exceed 100, and the number of datasets does not exceed 200.

Output:
For each dataset, output the hand's score on a new line.

Sample Input:
1
7 7 7
7 7 8
12 1
10 1 1
0

Output for the Sample Input:
11
21
0
21
12

# Buggy version:
if input() == '1':
    pass

while True:
    inp = input()
    if inp == '0': break


    inp = inp.replace('11', '10')
    inp = inp.replace('12', '10')
    inp = inp.replace('13', '10')

    cards = tuple(map(int, inp.split()))
    ans = sum(cards)

    for i in range(cards.count(1)):
        if sum(cards) + 10 * (i+1) > 21:
            break
        elif ans < sum(cards) + 10 * (i+1):
            ans = sum(cards) + 10 * (i+1)

    if ans > 21: ans = 0
    print(ans)

# Fixed version:
while True:
    inp = input()
    if inp == '0': break


    inp = inp.replace('11', '10')
    inp = inp.replace('12', '10')
    inp = inp.replace('13', '10')

    cards = tuple(map(int, inp.split()))
    ans = sum(cards)

    for i in range(cards.count(1)):
        if sum(cards) + 10 * (i+1) > 21:
            break
        elif ans < sum(cards) + 10 * (i+1):
            ans = sum(cards) + 10 * (i+1)

    if ans > 21: ans = 0
    print(ans)
Taro is engrossed in a novel series. The series consists of "n" volumes, each with varying thickness. He wants to buy a bookshelf dedicated to this series, but due to limited space, he needs to minimize the shelf width. He can place the bookshelf in "m" levels. The task is to determine how to divide the "n" volumes to minimize the shelf width. Taro insists that the volumes must be arranged in numerical order on each level. Given the number of levels, volume count, and thickness of each volume, create a program to find the minimum shelf width. The frame size of the bookshelf is not included in the width. The input consists of multiple datasets, each ending with two zeros. The output should display the minimum shelf width for each dataset. The width of the bookshelf will not exceed 1,500,000. The number of datasets will not exceed 50.

# Buggy version:

class Solve:
    def __init__(self):
        self.M, self.N = map(int, input().split())
        self.bs = [int(input()) for i in range(self.N)]

        self.S = min(sum(self.bs), 1500000)
        self.l, self.r = 0, self.S

    def check(self, W):
        w = W
        i = 1
        for b in self.bs:
            if(w >= b):
                w -= b
            elif(W >= b):
                if(i >= self.M):
                    return False
                i += 1
                w = W - b
            else:
                return False
        return True

    def solve(self):
        while self.r - self.l > 1:
            m = (self.l + self.r) // 2
            if self.check(m):
                self.r = m
            else:
                self.l = m
        return self.r

while True:
    print(Solve().solve())

# Fixed version:

class Solve:
    def __init__(self):
        self.M, self.N = map(int, input().split())
        self.bs = [int(input()) for i in range(self.N)]

        self.S = min(sum(self.bs), 1500000)
        self.l, self.r = 0, self.S        

    def check(self, W):
        w = W
        i = 1
        for b in self.bs:
            if(w >= b):
                w -= b
            elif(W >= b):
                if(i >= self.M):
                    return False
                i += 1
                w = W - b
            else:
                return False
        return True

    def solve(self):
        while self.r - self.l > 1:
            m = (self.l + self.r) // 2
            if self.check(m):
                self.r = m
            else:
                self.l = m
        return self.r

while True:
    s = Solve()
    if s.M == 0 and s.N == 0:
        break
    print(s.solve())
Title: 鶴ヶ城

The symbol of Aizuwakamatsu City, Tsurugajo Castle, was built by Gamo Ujisato with a full-fledged castle tower and named "Tsurugajo Castle." The Aizu Basin can be seen from the castle tower. On clear days, visitors can see Tsurugajo Castle from the mountaintop of Iimoriyama, famous for the Byakkotai.

For future public relations activities in Aizuwakamatsu City, a survey of the ages of visitors to Tsurugajo Castle has been decided. Create a program that takes the age of visitors as input and outputs the number of people in the following age groups for reference.

Input
Multiple datasets are given as input. The end of the input is indicated by a single line with a zero.
Each dataset is given in the following format.

n
a1
a2
:
an

The first line contains the number of visitors n (1 ≤ n ≤ 1000000), followed by n lines containing the age ai of the i-th visitor (0 ≤ ai ≤ 120).

Output
Output the number of people for each dataset in the following format.

1st line: Number of people under 10 years old
2nd line: Number of people in their teens
3rd line: Number of people in their twenties
4th line: Number of people in their thirties
5th line: Number of people in their forties
6th line: Number of people in their fifties
7th line: Number of people aged 60 and above

Sample Input
8
71
34
65
11
41
39
6
5
4
67
81
78
65
0

Output for the Sample Input
2
1
0
2
1
0
2
0
0
0
0
0
0
4

# Buggy version:
n=int(input())
x=[0 for i in range(7)]
while True:
  if n==0:
    break
  for i in range(n):
    a=int(input())
    if 0<=a<10:
      x[0]+=1
    elif 10<=a<20:
      x[1]+=1
    elif 20<=a<30:
      x[2]+=1
    elif 30<=a<40:
      x[3]+=1
    elif 40<=a<50:
      x[4]+=1 
    elif 50<=a<60:
      x[5]+=1
    else:
      x[6]+=1
  for i in range(7):
    if x[i]==0:
      print(0)
    else:
      print(x[i])


# Fixed version:
while True:
  x=[0 for i in range(7)]
  n=int(input())
  if n==0:
    break
  for i in range(n):
    a=int(input())
    if 0<=a<10:
      x[0]+=1
    elif 10<=a<20:
      x[1]+=1
    elif 20<=a<30:
      x[2]+=1
    elif 30<=a<40:
      x[3]+=1
    elif 40<=a<50:
      x[4]+=1 
    elif 50<=a<60:
      x[5]+=1
    else:
      x[6]+=1
  for i in range(7):
    print(x[i])

# Buggy version:
while True:
	n = int(input())
	ans = [0 for _ in range(7)]
	for _ in range(n):
		age = int(input())
		if age < 10:
			ans[0] += 1
		elif age < 20:
			ans[1] += 1
		elif age < 30:
			ans[2] += 1
		elif age < 40:
			ans[3] += 1
		elif age < 50:
			ans[4] += 1
		elif age < 60:
			ans[5] += 1
		else:
			ans[6] += 1
	for a in ans:
		print(a)

# Fixed version:
while True:
	n = int(input())
	if n == 0: break
	ans = [0 for _ in range(7)]
	for _ in range(n):
		age = int(input())
		if age < 10:
			ans[0] += 1
		elif age < 20:
			ans[1] += 1
		elif age < 30:
			ans[2] += 1
		elif age < 40:
			ans[3] += 1
		elif age < 50:
			ans[4] += 1
		elif age < 60:
			ans[5] += 1
		else:
			ans[6] += 1
	for a in ans:
		print(a)