Lucky tickets#128

Lucky tickets (Editorial)

Compute the number of three-digit numbers (which may start with zero) whose digits sum to . If we append any three-digit number with digit sum to another three-digit number with the same digit sum, we obtain a lucky ticket. Therefore, the number of lucky tickets is equal to p^2.

Example

Consider the case when n = 1. The three-digit numbers whose digits sum to are , , and . By concatenating any one of them with any other, we obtain lucky tickets.

Algorithm implementation

Read the input value of .

scanf("%d",&n);

The variable stores the number of three-digit numbers whose digits sum to .

p = 0;

Iterate over the digits of the three-digit number \overline{ijk}. If the sum of its digits is equal to , increment the value of by .

for(i = 0; i <= 9; i++)
for(j = 0; j <= 9; j++)
for(k = 0; k <= 9; k++)
  if (i + j + k == n) p++;

Compute and print the answer.

res = p * p;
printf("%d\n",res);

Java implementation

import java.util.*;

public class Main 
{
  public static void main(String args[]) 
  {
    Scanner con = new Scanner(System.in);
    int n = con.nextInt();
    int p = 0;
    for(int i = 0; i <= 9; i++)
    for(int j = 0; j <= 9; j++)
    for(int k = 0; k <= 9; k++)
      if (i + j + k == n) p++;
    
    int res = p * p;
    System.out.println(res);
    con.close();
  }
}

Python implementation

Read the input value of .

n = int(input())

The variable stores the number of three-digit numbers whose digits sum to .

p = 0

Iterate over the digits of the three-digit number \overline{ijk}. If the sum of its digits is equal to , increment the value of by .

for i in range(10):
  for j in range(10):
    for k in range(10):
      if (i + j + k == n): p += 1

Compute and print the answer.

res = p * p;
print(res)