package main

import "fmt"

func main() {
	var S, T string
	fmt.Scan(&S, &T)
	ans := "No"
	for i := 0; i < len(S); i++ {
		if S == T {
			ans = "Yes"
			break
		}
		S = S[len(S)-1:] + S[0:len(S)]
	}
	fmt.Println(ans)
}


package main

import(
  "fmt"
)

func main(){
  var S,T,R,Q string

  fmt.Scan(&S)
  fmt.Scan(&T)

  i := 0
  R=S

  for i<len(S){

    Q=R[len(R)-1:]
    R=R[:len(R)-1]
    R=Q+R

    fmt.Println(R)

    if R==T{
      fmt.Println("Yes")
      break
    }else{
      if i==len(S)-1{
        fmt.Println("No")
        break
      }
    }
    i++
  }
}


s,t = 2.times.map{gets.chomp.chars}

if s == t
  puts 'Yes'
  exit
end

if s.any?{s.rotate! == t}
  puts 'Yes'
else
  puts 'No'
end


s,t = 2.times.map{gets.chomp}

if s == t
  puts 'Yes'
  exit
end

s.size.times do |i|
  last = s.size-2
  s = s[-1] + s[0..last]
  if s == t
    puts 'Yes'
    exit
  end
end

puts 'No'


s = gets.chomp
t = gets.chomp

n = s.size

n.times do
  s = s[-1] + s[0..n-2]
  if s == t
    puts 'Yes'
    exit
  end
end
puts 'No'


require 'pp'
$DEBUG ? define_method(:dpp){|e|pp e} : define_method(:dpp){|e|}

# 入力値を文字の配列で返却する
def gets_nsp_list()
  gets.chomp.split("")
end

s = gets_nsp_list.sort
t = gets_nsp_list.sort

0.upto(s.size-1) do |i|
  if s[i] != t[i]
    puts "No"
    exit
  end
end

puts "Yes"


require 'pp'
$DEBUG ? define_method(:dpp){|e|pp e} : define_method(:dpp){|e|}

# 入力値を文字の配列で返却する
def gets_nsp_list()
  gets.chomp.split("")
end

s = gets_nsp_list.sort
t = gets_nsp_list.sort

if s == t
  puts "Yes"
else
  puts "No"
end


s = gets.chomp.split('')
t = gets.chomp.split('')
check = 0
n = s.size
if s.join('') != t.join('')
  n.times do
    tmp = s.pop
    s.unshift(tmp)
    check += 1 if s.join('') == t.join('')
  end
end
if check > 0
  puts :Yes
else
  puts:No
end


use std::io::*;
use std::str::FromStr;

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

fn main() {
    let s: String = read();
    let c: String = read();
    let mut sv: Vec<char> = s.chars().collect();
    let cv: Vec<char> = c.chars().collect();

    for _ in 0..s.len() {
        let a = sv.remove(0);
        sv.push(a);

        if sv == cv {
            println!("Yes");
            return;
        }

    }
    println!("No");
}


use std::io;

fn main() {
	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let s:Vec<char> = buf.trim().chars().collect();
	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let t:Vec<char> = buf.trim().chars().collect();
	let mut flag = false;

	for i in 0..s.len() {
		let s1 = &s[(s.len() - i - 1)..s.len()];
		let s2 = &s[0..(s.len() - i -1)];
		let t1 = &t[0..(i + 1)];
		let t2 = &t[(i + 1)..t.len()];
		if s1 == t1 && s2 == t2 {
			flag = true;
			break;
		}
	}
	if flag {
		println!("Yes");
	}else{
		println!("No");
	}
}


#[allow(unused_macros, dead_code)]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

#[allow(unused_macros, dead_code)]
macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};

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

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

#[allow(unused_macros, dead_code)]
macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };

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

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

    ($next:expr, bytes) => {
        read_value!($next, String).into_bytes()
    };

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

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

#[allow(dead_code)]
struct UnionFind {
    parent: Vec<usize>,
    rank: Vec<usize>,
    size: Vec<usize>,
}

#[allow(dead_code)]
impl UnionFind {
    fn new(n: usize) -> UnionFind {
        let mut p = vec![0; n];
        for i in 0..n {
            p[i] = i;
        }
        return UnionFind {
            parent: p,
            rank: vec![0; n],
            size: vec![1; n],
        };
    }

    fn find(&mut self, x: usize) -> usize {
        if x == self.parent[x] {
            x
        } else {
            let p = self.parent[x];
            let pr = self.find(p);
            self.parent[x] = pr;
            pr
        }
    }

    fn same(&mut self, a: usize, b: usize) -> bool {
        self.find(a) == self.find(b)
    }

    fn unite(&mut self, a: usize, b: usize) {
        let a_root = self.find(a);
        let b_root = self.find(b);
        if a_root == b_root {
            return;
        }
        if self.rank[a_root] > self.rank[b_root] {
            self.parent[b_root] = a_root;
            self.size[a_root] += self.size[b_root];
        } else {
            self.parent[a_root] = b_root;
            self.size[b_root] += self.size[a_root];
            if self.rank[a_root] == self.rank[b_root] {
                self.rank[b_root] += 1;
            }
        }
    }

    fn get_size(&mut self, x: usize) -> usize {
        let root = self.find(x);
        self.size[root]
    }
}

const MOD_P: usize = 1000000007;

#[allow(dead_code)]
// fact(n) = n! mod p
fn fact(n: usize) -> usize {
    let mut acc = 1;
    for i in 1..n + 1 {
        acc = acc * i % MOD_P;
    }
    acc
}

#[allow(dead_code)]
fn mod_pow(b: usize, mut e: usize) -> usize {
    let mut base = b;
    let mut acc = 1;

    while e > 1 {
        if e % 2 == 1 {
            acc = acc * base % MOD_P;
        }
        e /= 2;
        base = base * base % MOD_P;
    }

    if e == 1 {
        acc = acc * base % MOD_P;
    }

    acc
}

#[allow(dead_code)]
fn comb(n: usize, r: usize) -> usize {
    // nCr = n! / (r! (n-r)!) = n! (r!)^(p-2) ((n-r)!)^(p-2)
    let x = ((n - r + 1)..(n + 1)).fold(1, |p, x| p * x % MOD_P);
    let y = mod_pow(fact(r), MOD_P - 2);
    x * y % MOD_P
}

#[allow(dead_code)]
fn gcd(a: usize, b: usize) -> usize {
    if b > a {
        gcd(b, a)
    } else if a % b == 0 {
        b
    } else {
        gcd(b, a % b)
    }
}

#[allow(dead_code)]
fn getline() -> String {
    let mut __ret = String::new();
    std::io::stdin().read_line(&mut __ret).ok();
    return __ret;
}

use std::cmp::{max, min};

fn main() {
    input! {
        s: chars,
        t: chars,
    }
    let n = s.len();
    'outer: for d in 0..n {
        for i in 0..n {
            let j = (i + d) % n;
            if s[i] != t[j] {
                continue 'outer;
            }
        }
        println!("Yes");
        return;
    }
    println!("No");
}


use std::io;

fn main() {
	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let s = buf.trim().to_string();
	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let t = buf.trim().to_string();
	let mut flag = false;
	let mut rots = String::new();
	rots = s;
	for i in 0..rots.len() {
		let s1 = &rots[0..(rots.len() - 1)];
		let s2 = &rots[(rots.len()-1)..rots.len()];
		s = format!("{}{}", s2, s1);

		if s == t {
			flag = true;
			break;
		}
		rots = s;
	}
	if flag {
		println!("Yes");
	}else{
		println!("No");
	}
}


use std::io;

fn main() {
	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let s = buf.trim().to_string();
	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let t = buf.trim().to_string();
	let mut flag = false;
	let mut rots = String::new();
	rots = s;
	for i in 0..rots.len() {
		let s1 = &rots[0..(rots.len() - 1)];
		let s2 = &rots[(rots.len()-1)..rots.len()];
		rots = format!("{}{}", s2, s1);

		if rots == t {
			flag = true;
			break;
		}
	}
	if flag {
		println!("Yes");
	}else{
		println!("No");
	}
}


use std::io;

fn main() {
	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let s = buf.trim();
	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let t = buf.trim();
	let mut flag = false;
	for i in 1..(t.len() + 1) {
		let s1 = &s[(s.len() - i)..s.len()];
		let t1 = &t[0..i];
		if s1 == t1 {
			flag = true;
			break;
		}
	}
	if flag {
		println!("Yes");
	}else{
		println!("No");
	}
}


import Foundation
var s = readLine()!
let t = readLine()!
for _ in 0..<t.count {
  if s == t {
    print("Yes")
    exit(0)
  }
  let c = s[s.index(s.endIndex, offsetBy: -1)]
  s = "\(c)\(String(s.dropLast()))"
}
print("No")


import Foundation

#if swift(>=4.0)
extension String {
    func split(by separator: String) -> [String] {
        return self.components(separatedBy: separator)
    }
    func toArray() -> [String] {
        return self.map{String($0)}
    }
}
#else
extension String {
    func split(by separator: String) -> [String] {
        return self.componentsSeparatedByString(separator)
    }
    var count: Int {
        return self.characters.count
    }
    func toArray() -> [String] {
        return self.characters.map{String($0)}
    }
    func uppercased() -> String {
        return self.uppercaseString
    }
    func lowercased() -> String {
        return self.lowercaseString
    }
}
extension Array where Element: Comparable {
    func max() -> Element {
        return self.maxElement()!
    }
    func min() -> Element {
        return self.minElement()!
    }
    func sorted() -> Array {
        return self.sort()
    }
    func reversed() -> Array {
        return self.reverse()
    }
    mutating func sort() {
        self.sortInPlace()
    }
}
extension Array {
    init(repeating: Element, count: Int) {
        self.init(count: count, repeatedValue: repeating)
    }
}
func stride<T: Strideable>(from start: T, to end: T, by stride: T.Stride) -> StrideTo<T> {
    return start.stride(to: end, by: stride)
}
#endif
func readInt() -> Int? {
    return Int(readLine()!)
}
func readStringSplit(by separator: String) -> [String] {
    return readLine()!.split(by: separator)
}
func readIntSplit(by separator: String) -> [Int] {
    return readLine()!.split(by: separator).map{Int($0)!}
}

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

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

var S = readLine()!.toArray() + [""]              // 100 + 1 -> 101
let T = readLine()!
var ans = "No"
for _ in 0..<S.count {
    for i in ((0..<S.count).map{$0}).reversed() { // (0..<101).reversed() -> (100...0)
        if i > 0 {
            S[i] = S[i-1]                         // S[100] = S[99]
        } else {
            S[i] = S[S.count-1]                   // S[0] = S[100]
            S[S.count-1] = ""
        }
    }
    if S.joinWithSeparator("") == T {
        ans = "Yes"
        break
    }
}
print(ans)


//
//  main.swift
//  AtCoderSwift
//
//  Created by burita083 on 2020/08/25.
//  Copyright © 2020 burita083. All rights reserved.
//

import Foundation
func readInt() -> Int {
    return Int(readLine()!)!
}

func readInts() -> [Int] {
    return readLine()!.split(separator: " ").map { Int($0)! }
}

func readTwoInts() -> (a: Int, b: Int) {
    let ints = readLine()!.split(separator: " ").map { Int($0)! }
    return (a: ints[0], b: ints[1])
}

func abc080_b() {
    let N = readLine()!
    let sum = N.map { Int(String($0))! }.reduce(0, +)
    print(Int(N)! % sum == 0 ? "Yes" : "No")
}

//abc080_b()

func abc078_b() {
    let input = readInts()
    var X = input[0]
    let Y = input[1]
    let Z = input[2]
    var ans = 0
    X -= Y+Z*2
    ans += 1
    ans += X/(Y+Z)

    print(ans)
}

func abc085_b() {
    let N = readInt()
    var l: [Int] = []
    for _ in 0..<N {
        let d = readInt()
        l.append(d)
    }
    print(l.reduce([], { $0.contains($1) ? $0 : $0 + [$1] }).count)
}

func isSquare(n: Double) -> Bool {
    let sqrt = floor(n.squareRoot())
    return sqrt * sqrt == n
}

func abc077_b() {
    let N = readInt()
    for n in (1...N).reversed() {
        if isSquare(n: Double(n)) {
            print(n)
            return
        }
    }
}

func abc020_b () {
    let inputs = readInts()
    print(Int(String(inputs[0]) + String(inputs[1]))! * 2)
}

func abc073_b () {
    var ans = 0
    let N = readInt()
    for _ in 0..<N {
        let inputs = readInts()
        ans += inputs[1] - inputs[0] + 1
    }
    print(ans)
}

func abc026_b () {
    var evens: [Int] = []
    var odds: [Int] = []
    var all: [Int] = []
    let N = readInt()
    for _ in 0..<N {
        let R = readInt()
        all.append(R)
    }

    for (i, e) in all.sorted(by: >).enumerated() {
        if i % 2 == 0 {
            evens.append(e)
        } else {
            odds.append(e)
        }
    }
    let ans = evens.map { $0 * $0 }.reduce(0, +) - odds.map { $0 * $0 }.reduce(0, +)
    print(Double(ans) * Double.pi)
}

extension StringProtocol {
    var firstUppercased: String {
        return prefix(1).uppercased()  + self.lowercased().dropFirst()
    }
}

func abc012_b () {
    print(readLine()!.firstUppercased)

}

func abc007_b () {
    print(readLine()! == "a" ? -1 : "a")
}

func abc028_b () {
    let S = readLine()!
    let A = String(S.filter { $0 == "A" }.count)
    let B = String(S.filter { $0 == "B" }.count)
    let C = String(S.filter { $0 == "C" }.count)
    let D = String(S.filter { $0 == "D" }.count)
    let E = String(S.filter { $0 == "E" }.count)
    let F = String(S.filter { $0 == "F" }.count)
    print(A + " " + B + " " + C + " " + D + " " + E + " " + F)
}

func abc097_b () {
    let x = Double(Int(readLine()!)!)
    var ans: Double = 1
    for b in 2..<32 {
        var p: Double = 2
        while pow(Double(b), p) <= x {
            ans = max(ans, pow(Double(b), p))
            p += 1
        }
    }
    print(Int(ans))
}

func abc093_b () {
    var ans: [Int] = []
    let inputs = readInts()
    for x in inputs[0]..<inputs[0]+inputs[2] {
        ans.append(x)
    }

    for x in inputs[1]-inputs[2]+1...inputs[1] {
        if !ans.contains(x) {
            ans.append(x)
        }
    }
    ans.filter { $0 >= inputs[0] && $0 <= inputs[1] }.forEach { print($0) }

}

extension String {
    subscript(i: Int) -> String {
        return String(self[index(startIndex, offsetBy: i)])
    }
}

func abc071_b () {
    let S = readLine()!
    let T = readLine()!
    if S == T {
        print("Yes")
        return
    }

    var ans = 0
    var count: Int
    for i in 0..<T.count {
        count = 0
        for k in i..<T.count {
            if S[k] == T[k] {
                count += 1
            }
        }

        for k in 0..<i {
            if S[k] == T[k] {
                count += 1
            }
        }
        ans = max(ans, count)
    }

    if ans == T.count {
        print("Yes")
    } else {
        print("No")
    }

}

abc071_b()


//
//  main.swift
//  AtCoderSwift
//
//  Created by burita083 on 2020/08/25.
//  Copyright © 2020 burita083. All rights reserved.
//

import Foundation
func readInt() -> Int {
    return Int(readLine()!)!
}

func readInts() -> [Int] {
    return readLine()!.split(separator: " ").map { Int($0)! }
}

func readTwoInts() -> (a: Int, b: Int) {
    let ints = readLine()!.split(separator: " ").map { Int($0)! }
    return (a: ints[0], b: ints[1])
}

func abc080_b() {
    let N = readLine()!
    let sum = N.map { Int(String($0))! }.reduce(0, +)
    print(Int(N)! % sum == 0 ? "Yes" : "No")
}

//abc080_b()

func abc078_b() {
    let input = readInts()
    var X = input[0]
    let Y = input[1]
    let Z = input[2]
    var ans = 0
    X -= Y+Z*2
    ans += 1
    ans += X/(Y+Z)

    print(ans)
}

func abc085_b() {
    let N = readInt()
    var l: [Int] = []
    for _ in 0..<N {
        let d = readInt()
        l.append(d)
    }
    print(l.reduce([], { $0.contains($1) ? $0 : $0 + [$1] }).count)
}

func isSquare(n: Double) -> Bool {
    let sqrt = floor(n.squareRoot())
    return sqrt * sqrt == n
}

func abc077_b() {
    let N = readInt()
    for n in (1...N).reversed() {
        if isSquare(n: Double(n)) {
            print(n)
            return
        }
    }
}

func abc020_b () {
    let inputs = readInts()
    print(Int(String(inputs[0]) + String(inputs[1]))! * 2)
}

func abc073_b () {
    var ans = 0
    let N = readInt()
    for _ in 0..<N {
        let inputs = readInts()
        ans += inputs[1] - inputs[0] + 1
    }
    print(ans)
}

func abc026_b () {
    var evens: [Int] = []
    var odds: [Int] = []
    var all: [Int] = []
    let N = readInt()
    for _ in 0..<N {
        let R = readInt()
        all.append(R)
    }

    for (i, e) in all.sorted(by: >).enumerated() {
        if i % 2 == 0 {
            evens.append(e)
        } else {
            odds.append(e)
        }
    }
    let ans = evens.map { $0 * $0 }.reduce(0, +) - odds.map { $0 * $0 }.reduce(0, +)
    print(Double(ans) * Double.pi)
}

extension StringProtocol {
    var firstUppercased: String {
        return prefix(1).uppercased()  + self.lowercased().dropFirst()
    }
}

func abc012_b () {
    print(readLine()!.firstUppercased)

}

func abc007_b () {
    print(readLine()! == "a" ? -1 : "a")
}

func abc028_b () {
    let S = readLine()!
    let A = String(S.filter { $0 == "A" }.count)
    let B = String(S.filter { $0 == "B" }.count)
    let C = String(S.filter { $0 == "C" }.count)
    let D = String(S.filter { $0 == "D" }.count)
    let E = String(S.filter { $0 == "E" }.count)
    let F = String(S.filter { $0 == "F" }.count)
    print(A + " " + B + " " + C + " " + D + " " + E + " " + F)
}

func abc097_b () {
    let x = Double(Int(readLine()!)!)
    var ans: Double = 1
    for b in 2..<32 {
        var p: Double = 2
        while pow(Double(b), p) <= x {
            ans = max(ans, pow(Double(b), p))
            p += 1
        }
    }
    print(Int(ans))
}

func abc093_b () {
    var ans: [Int] = []
    let inputs = readInts()
    for x in inputs[0]..<inputs[0]+inputs[2] {
        ans.append(x)
    }

    for x in inputs[1]-inputs[2]+1...inputs[1] {
        if !ans.contains(x) {
            ans.append(x)
        }
    }
    ans.filter { $0 >= inputs[0] && $0 <= inputs[1] }.forEach { print($0) }

}

extension String {
    subscript(i: Int) -> String {
        return String(self[index(startIndex, offsetBy: i)])
    }
}

func abc071_b () {
    let S = readLine()!
    let T = readLine()!
    if S == T {
        print("Yes")
        return
    }

    var ans = 0
    var count: Int
    for i in 0..<T.count {
        count = 0
        for k in i..<T.count {
            if S[k] == T[k] {
                count += 1
            }
        }

        for k in 0..<i {
            if S[k] == T[k] {
                count += 1
            }
        }
        ans = max(ans, count)
    }

    if ans == T.count {
        print("Yes")
    }

}

abc071_b()


//
//  main.swift
//  AtCoderSwift
//
//  Created by burita083 on 2020/08/25.
//  Copyright © 2020 burita083. All rights reserved.
//

import Foundation
func readInt() -> Int {
    return Int(readLine()!)!
}

func readInts() -> [Int] {
    return readLine()!.split(separator: " ").map { Int($0)! }
}

func readTwoInts() -> (a: Int, b: Int) {
    let ints = readLine()!.split(separator: " ").map { Int($0)! }
    return (a: ints[0], b: ints[1])
}

func abc080_b() {
    let N = readLine()!
    let sum = N.map { Int(String($0))! }.reduce(0, +)
    print(Int(N)! % sum == 0 ? "Yes" : "No")
}

//abc080_b()

func abc078_b() {
    let input = readInts()
    var X = input[0]
    let Y = input[1]
    let Z = input[2]
    var ans = 0
    X -= Y+Z*2
    ans += 1
    ans += X/(Y+Z)

    print(ans)
}

func abc085_b() {
    let N = readInt()
    var l: [Int] = []
    for _ in 0..<N {
        let d = readInt()
        l.append(d)
    }
    print(l.reduce([], { $0.contains($1) ? $0 : $0 + [$1] }).count)
}

func isSquare(n: Double) -> Bool {
    let sqrt = floor(n.squareRoot())
    return sqrt * sqrt == n
}

func abc077_b() {
    let N = readInt()
    for n in (1...N).reversed() {
        if isSquare(n: Double(n)) {
            print(n)
            return
        }
    }
}

func abc020_b () {
    let inputs = readInts()
    print(Int(String(inputs[0]) + String(inputs[1]))! * 2)
}

func abc073_b () {
    var ans = 0
    let N = readInt()
    for _ in 0..<N {
        let inputs = readInts()
        ans += inputs[1] - inputs[0] + 1
    }
    print(ans)
}

func abc026_b () {
    var evens: [Int] = []
    var odds: [Int] = []
    var all: [Int] = []
    let N = readInt()
    for _ in 0..<N {
        let R = readInt()
        all.append(R)
    }

    for (i, e) in all.sorted(by: >).enumerated() {
        if i % 2 == 0 {
            evens.append(e)
        } else {
            odds.append(e)
        }
    }
    let ans = evens.map { $0 * $0 }.reduce(0, +) - odds.map { $0 * $0 }.reduce(0, +)
    print(Double(ans) * Double.pi)
}

extension StringProtocol {
    var firstUppercased: String {
        return prefix(1).uppercased()  + self.lowercased().dropFirst()
    }
}

func abc012_b () {
    print(readLine()!.firstUppercased)

}

func abc007_b () {
    print(readLine()! == "a" ? -1 : "a")
}

func abc028_b () {
    let S = readLine()!
    let A = String(S.filter { $0 == "A" }.count)
    let B = String(S.filter { $0 == "B" }.count)
    let C = String(S.filter { $0 == "C" }.count)
    let D = String(S.filter { $0 == "D" }.count)
    let E = String(S.filter { $0 == "E" }.count)
    let F = String(S.filter { $0 == "F" }.count)
    print(A + " " + B + " " + C + " " + D + " " + E + " " + F)
}

func abc097_b () {
    let x = Double(Int(readLine()!)!)
    var ans: Double = 1
    for b in 2..<32 {
        var p: Double = 2
        while pow(Double(b), p) <= x {
            ans = max(ans, pow(Double(b), p))
            p += 1
        }
    }
    print(Int(ans))
}

func abc093_b () {
    var ans: [Int] = []
    let inputs = readInts()
    for x in inputs[0]..<inputs[0]+inputs[2] {
        ans.append(x)
    }

    for x in inputs[1]-inputs[2]+1...inputs[1] {
        if !ans.contains(x) {
            ans.append(x)
        }
    }
    ans.filter { $0 >= inputs[0] && $0 <= inputs[1] }.forEach { print($0) }

}

extension String {
    subscript(i: Int) -> String {
        return String(self[index(startIndex, offsetBy: i)])
    }
}

func abc071_b () {
    let S = readLine()!
    let T = readLine()!
    if S == T {
        print("Yes")
        return
    }

    var ans = 0
    var count: Int
    for i in 0..<T.count {
        count = 0
        for k in i..<T.count {
            if S[k] == T[k] {
                count += 1
            }
        }

        for k in 0..<i {
            if S[k] == T[k] {
                count += 1
            }
        }
        ans = max(ans, count)
    }
    if ans == T.count {
        print("Yes")
    }

}

abc071_b()


const input=require('fs').readFileSync('/dev/stdin','utf8').split(/[\s]/);const tn=():number=>{const a=input[0];input.shift();return Number(a)};const tnn=(n:number):number[]=>{const a=[];for(let i=0;i<n;i++){a.push(tn())}return a};const ts=():string=>{const a=input[0];input.shift();return String(a)};const tss=(n:number):string[]=>{const a=[];for(let i=0;i<n;i++){a.push(ts())}return a};const tc=():string=>{let a=input[0].split('');const b=a[0];a.shift();if(a.length>0){input[0]=a.join('')}else{input.shift()}return String(b)};const tcc=(n:number):string[]=>{const a=[];for(let i=0;i<n;i++){a.push(tc())}return a};const to=(...arg)=>{console.log(...arg)};const abs=(a)=>{return Math.abs(a)};const min=(...a)=>{return Math.min(...a)};const max=(...a)=>{return Math.max(...a)};const floor=(a)=>{return Math.floor(a)};const asc=(ar:number[])=>{return ar.sort((a,b)=>{return a-b})};const desc=(ar:number[])=>{return ar.sort((a,b)=>{return b-a})};const sw=(a,arr:any[],op:'=='|'>='|'>'|'<='|'<'='==')=>{for(let i=0;i<arr.length;i+=2){if(eval(a+op+arr[i]))return arr[i+1];}return arr[arr.length-1]};const near=(n:number,arr:number[]):number=>{let ne=arr[0],ni=0;for(let i=1;i<arr.length;i++){if(Math.abs(n-ne)>Math.abs(n-arr[i])){ne=arr[i];ni=i}}return ni};
const main=()=>{
  let s=ts().split('')
  let t=ts()
  for(let i=0;i<s.length;i++){
    if(s.join('')===t){
      to('Yes')
      return
    }
    s.unshift(s[s.length-1])
    s.pop()
  }
  to('No')
}
main()


declare var require: (x: string) => any;

function Main(input: string[]) {
  const [s, t] = input;
  console.log((s+s).indexOf(t) >= 0 ? 'Yes' : 'No');
}

Main(require('fs').readFileSync('/dev/stdin', 'utf8').split('\n'));


const stdin = require('fs').readFileSync('/dev/stdin', 'utf8')

const [s, t] = stdin.trim().split('\n')

const ans = _ => {
  let sArr = s.split('')
  for (let i = 0; i < sArr.length; i++) {
    const last = sArr[sArr.length - 1]
    sArr = [last, ...sArr]
    sArr.pop()

    const str = sArr.join('')

    if (str === t) return 'Yes'
  }
  return 'No'
}

console.log(ans())


const input=require('fs').readFileSync('/dev/stdin','utf8').split(/[\s]/);const tn=():number=>{const a=input[0];input.shift();return Number(a)};const tnn=(n:number):number[]=>{const a=[];for(let i=0;i<n;i++){a.push(tn())}return a};const ts=():string=>{const a=input[0];input.shift();return String(a)};const tss=(n:number):string[]=>{const a=[];for(let i=0;i<n;i++){a.push(ts())}return a};const tc=():string=>{let a=input[0].split('');const b=a[0];a.shift();if(a.length>0){input[0]=a.join('')}else{input.shift()}return String(b)};const tcc=(n:number):string[]=>{const a=[];for(let i=0;i<n;i++){a.push(tc())}return a};const to=(...arg)=>{console.log(...arg)};const abs=(a)=>{return Math.abs(a)};const min=(...a)=>{return Math.min(...a)};const max=(...a)=>{return Math.max(...a)};const floor=(a)=>{return Math.floor(a)};const asc=(ar:number[])=>{return ar.sort((a,b)=>{return a-b})};const desc=(ar:number[])=>{return ar.sort((a,b)=>{return b-a})};const sw=(a,arr:any[],op:'=='|'>='|'>'|'<='|'<'='==')=>{for(let i=0;i<arr.length;i+=2){if(eval(a+op+arr[i]))return arr[i+1];}return arr[arr.length-1]};const near=(n:number,arr:number[]):number=>{let ne=arr[0],ni=0;for(let i=1;i<arr.length;i++){if(Math.abs(n-ne)>Math.abs(n-arr[i])){ne=arr[i];ni=i}}return ni};
const main=()=>{
  let s=ts().split('')
  let t=ts()
  for(let i=1;i<s.length;i++){
    s.unshift(s[s.length-1])
    s.pop()
    if(s.join('')===t){
      to('Yes')
      return
    }
  }
  to('No')
}
main()


n, a, b = (int(x) for x in input().split())
c = 0
sum = 0
for i in range(1, n+1):
  c += 1
  if a <= c <= b:
    sum += i
  while i%10 == 9:
    c -= 9
    i //= 10
print(sum)


from sys import stdin
N, A, B = [int(x) for x in stdin.readline().rstrip().split()]
#N, A, B = map(int, input().split())
n_list = [0]
#digit3_max = min(int(N / 100), 9)
digit_N = len(str(N))

def setDigit(N_max, sum_min, sum_max, digit):
    n_max = int(N_max / (10 ** (digit - 1)))
    for i in range(min(n_max, sum_max, 9) + 1):
        if digit == 1 and i >= sum_min:
            n_list.append(N - N_max + i)
            #print(N_max, i)
        elif digit == 1 and i < sum_min: continue
        else:
            #print(N_max - (i * 10 ** (digit - 1)), max(sum_min - i, 0), sum_max - i, digit - 1)
            setDigit(N_max - (i * 10 ** (digit - 1)), max(sum_min - i, 0), sum_max - i, digit - 1)

setDigit(N, A, B, digit_N)
'''
for digit3 in range(digit3_max + 1):
    tmp1 = N - digit3 * 100
    digit2_max = min(int(tmp1 / 10), 9)
    for digit2 in range(digit2_max + 1):
        tmp2 = tmp1 - digit2 * 10
        digit1_max = min(tmp2, 9)
        for digit1 in range(digit1_max + 1):
            if (digit1 + digit2 + digit3) >= A and (digit1 + digit2 + digit3) <= B:
                n_list.append(digit3 * 100 + digit2 * 10 + digit1)
'''

print(sum(n_list))


N, A, B = map(int, input().split())
n_list = [0]
digit_N = len(str(N))

def setDigit(N_max, sum_min, sum_max, digit):
    n_max = int(N_max / (10 ** (digit - 1)))
    for i in range(min(n_max, sum_max, 9) + 1):
        if digit == 1 and i >= sum_min:
            n_list.append(N - N_max + i)
        elif digit == 1 and i < sum_min: continue
        else:
            setDigit(N_max - (i * 10 ** (digit - 1)), max(sum_min - i, 0), sum_max - i, digit - 1)

setDigit(N, A, B, digit_N)

print(sum(n_list))


N,A,B = map(int,input().split())
ans_list = []

for i in range(0,N+1):
    if i < 10:
        if i >= A and i <=B:
            ans_list.append(i)
    else:
        temp = list(map(int,str(i)))
        temp = temp[0]+temp[1]
        if temp >=A and temp<=B:
            ans_list.append(i)

print(sum(ans_list))


N = int(input())
A = int(input())
B = int(input())
ans_list = []

for i in range(0,N+1):
    if i < 10:
        if i >= A and i <=B:
            ans_list.append(i)
    else:
        temp = list(map(int,str(i)))
        temp = temp[0]+temp[1]
        if temp >=A and temp<=B:
            ans_list.append(i)

print(sum(ans_list))


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
	public static void main(String[] args) throws IOException {
		BufferedReader buff = null;
		buff = new BufferedReader(new InputStreamReader(System.in));

		String[] box = buff.readLine().split(" ");
		int N = Integer.parseInt(box[0]);
		int A = Integer.parseInt(box[1]);
		int B = Integer.parseInt(box[2]);

		int count = 0;
		while(N > 0){
			int total = 0;
			int pre = N;
			while(pre > 0){
				total += pre % 10;
				pre = pre / 10;
				//System.out.println(" / " + pre + " " + total);
			}
			if(total >= A && total <= B){
				//System.out.println(" * " + total + " " + N);
				count += N;
			}
			N--;
		}

		System.out.println(count);
	}

	static long f() {
		long ans = 0;

		return ans;
	}
}


import java.io.IOException;
import java.io.InputStream;
import java.util.NoSuchElementException;

public class Main {

	public static void main(String[] args) {

		FastScanner sc = new FastScanner();
		int N = sc.nextInt();
		int A = sc.nextInt();
		int B = sc.nextInt();
		int ans = 0;
		for (int i = 1; i <= N; i++) {
			if (i / 10 == 0) {
				if (A <= i && i <= B)
					ans += i;
			} else if (i / 100 == 0) {
				if (A <= i % 10 + i / 10 && i % 10 + i / 10 <= B)
					ans += i;
			} else if (i / 1000 == 0) {
				if (A <= i % 10 + i % 100 / 10 + i / 100 && i % 10 + i % 100 / 10 + i / 100 <= B)
					ans += i;
			} else if (i / 10000 == 0) {
				if (A <= i % 10 + i % 100 / 10 + i % 1000 / 100 + i / 1000
						&& i % 10 + i % 100 / 10 + i % 1000 / 100 + i / 1000 <= B)
					ans += i;
			} else if (i == 10000) {
				if (A <= 1 && 1 <= B)
					ans += i;
			}
		}
		System.out.println(ans);

	}
	//以下、自作ライブラリ

	//最大公約数
	public static long gcd(long a, long b) {
		if (a < b)
			return gcd(b, a);
		long c = 0;
		c = a % b;
		if (c == 0)
			return b;
		return gcd(b, c);
	}

	//最小公倍数
	public static long lcm(long m, long n) {
		return m * n / gcd(m, n);
	}

	//素数判定
	public static boolean isPrime(int n) {
		if (n < 2)
			return false;
		if (n == 2)
			return true;
		if (n % 2 == 0)
			return false;

		for (int i = 3; i * i <= n; i += 2) {
			if (n % i == 0)
				return false;
		}
		return true;
	}
}

//以下、高速スキャナークラス
class FastScanner {
	private final InputStream in = System.in;
	private final byte[] buffer = new byte[1024];
	private int ptr = 0;
	private int buflen = 0;

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

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

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

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

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

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

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

	public double nextDouble() {
		return Double.parseDouble(next());
	}
}


import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.NoSuchElementException;

public class Main {
	static FastScanner sc = new FastScanner();
	static PrintWriter out = new PrintWriter(System.out);

	public static void main(String[] args) {
		int n = sc.nextInt();
		int a = sc.nextInt();
		int b = sc.nextInt();

		int cnt = 0;

		for (int i=1; i<=n; i++){
			int c = i%10;
			int d = (i/10)%10;
			int e = (i/100)%10;
			int f = (i/1000)%10;

			if ((c+d+e+f)>=a && (c+d+e+f)<=b)
				cnt+=i;
		}

		if (n==10000){
			if (a==1)
				cnt+=10000;
		}
		out.println(cnt);

		out.flush();
	}

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

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

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

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

		    private void skipUnprintable() {
		      while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++;
		    }

		    public boolean hasNext() {
		      skipUnprintable();
		      return hasNextByte();
		    }

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

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

		    public int nextInt() {
		      return (int) nextLong();
		    }

		    public int[] nextIntArray(int N, boolean oneBased) {
		      if (oneBased) {
		        int[] array = new int[N + 1];
		        for (int i = 1; i <= N; i++) {
		          array[i] = sc.nextInt();
		        }
		        return array;
		      } else {
		        int[] array = new int[N];
		        for (int i = 0; i < N; i++) {
		          array[i] = sc.nextInt();
		        }
		        return array;
		      }
		    }

		    public long[] nextLongArray(int N, boolean oneBased) {
		      if (oneBased) {
		        long[] array = new long[N + 1];
		        for (int i = 1; i <= N; i++) {
		          array[i] = sc.nextLong();
		        }
		        return array;
		      } else {
		        long[] array = new long[N];
		        for (int i = 0; i < N; i++) {
		          array[i] = sc.nextLong();
		        }
		        return array;
		      }
		    }
		  }

		}


import java.util.*;

class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int a = sc.nextInt();
      	int b = sc.nextInt();
		int sho = 0;
      	int amrs = 0;
	    int ans = 0;

      for(int i = 1 ; i < n+1 ; i++){
        sho = i;
        amrS= 0;
      	while(sho != 0){
          amrS += sho%10;
          sho /= 10;
        }
        if(amrS >= a && amrS <= b){
        	ans += i;
        }
      }
                  System.out.println(ans);
    }
}


import java.util.*;

class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int a = sc.nextInt();
      	int b = sc.nextInt();
		int sho, amrS;
	    int ans = 0;
      for(int i = 1 ; i < n+1 ; i++){
        sho = i;
        amrS= 0;
      	while(sho != 0){
          sho /= 10;
          amrS += sho%10;
        }
        if(amrS >= a && amrS <= b){
        	ans += i;
        }
      }
                  System.out.println(ans);
    }
}


import java.util.*;

class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int a = sc.nextInt();
      	int b = sc.nextInt();
		int sho, amrs;
	    int ans = 0;
      for(int i = 1 ; i < n+1 ; i++){
        sho = i;
        amrS= 0;
      	while(sho != 0){
          sho /= 10;
          amrS += sho%10;
        }
        if(amrS >= a && amrS <= b){
        	ans += i;
        }
      }
                  System.out.println(ans);
    }
}


#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define il inline
#define outy printf("Yes\n")
#define outn printf("No\n")
#define outf printf("First\n")
#define outs printf("Second\n")
#define FOR(a,b,c) for(int a=b;a<=c;a++)
#define FORD(a,b,c) for(int a=b;a>=c;a--)
#define FORL(a,b) for(int a=head[b];a;a=nxt[a])
#define in(a)  a=read()
#define in2(a,b)  a=read(),b=read()
#define in3(a,b,c)  a=read(),b=read(),c=read()
#define in4(a,b,c,d)  a=read(),b=read(),c=read(),d=read()
#define inl(a)  a=readl()
#define inl2(a,b)  a=readl(),b=readl()
#define inl3(a,b,c)  a=readl(),b=readl(),c=readl()
#define inl4(a,b,c,d)  a=readl(),b=readl(),c=readl(),d=readl()
#define out(a) printf("%d\n",a)
#define out2(a,b) printf("%d %d\n",a,b)
#define out3(a,b,c) printf("%d %d %d\n",a,b,c)
#define out4(a,b,c,d) printf("%d %d %d %d\n",a,b,c,d)
#define outl(a) printf("%lld\n",a)
#define outl2(a,b) printf("%lld %lld\n",a,b)
#define outl3(a,b,c) printf("%lld %lld %lld\n",a,b,c)
#define outl4(a,b,c,d) printf("%lld %lld %lld %lld\n",a,b,c,d)
#define clr(x,y) memset(x,y,sizeof(x))
inline int read(){
    char c;int s=0,t=1;
    while(!isdigit(c=getchar()))if(c=='-')t=-1;
    do{s=s*10+c-'0';}while(isdigit(c=getchar()));
    return s*t;
}
inline ll readl(){
    char c;ll s=0;int t=1;
    while(!isdigit(c=getchar()))if(c=='-')t=-1;
    do{s=s*10+c-'0';}while(isdigit(c=getchar()));
    return s*t;
}
/*------------------------------------------------------------*/
#define mod 1000000000
#define maxn 110
#define inf 0x7fffffff
/*------------------------------------------------------------*/
int n,m;
int a,b;
bool check(int x){
	int ans=0;
	while(x){
		ans+=x%10;
		x/=10;
	}
	return ans>=a&&ans<=b;
}
int main(){
	in(n);
	in2(a,b);
	int ans=0;
	FOR(i,1,n){
		if(check(i))ans+=i;
	}
	out(ans);
}


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef unsigned long long ull;

#define FOR(i,a,b) for(int i=(a);i<(b);i++)
#define RFOR(i,a,b) for(int i=(b)-1;i>=(a);i--)
#define REP(i,n) for(int i=0;i<(n);i++)
#define RREP(i,n) for(int i=(n)-1;i>=0;i--)
#define VSORT(v) sort(v.begin(), v.end())
#define DVSORT(v) sort(v.begin(), v.end(),greater<int>())
#define SORT(v, n) sort(v, v+n)
#define DSORT(v,n) sort(v, v+n,greater<int>())
#define vi vector<int>
#define pb push_back
#define P pair<int,int>

template <class T> void chmin(T&a,const T&b) { a = min(a,b); }
template <class T> void chmax(T&a,const T&b) { a = max(a,b); }

void print(){cout<<endl;}
template <class Head, class... Tail>
void print(Head&& h,Tail&&... t){
	if(sizeof...(t)==0)
		cout<<h;
	else
		cout<<h<<' ';
	print(move(t)...);
}

const double EPS =1e-9;
const long INF =2147483647;//32bit 2*1e+9
const long MOD =1e+9+7;
#define PI 3.14159265258979

int dy[]={0, 0, 1, -1, 1, 1, -1, -1};
int dx[]={1, -1, 0, 0, 1, -1, -1, 1};

int fn(int i){
	if(i<=9) return i;
	else return i%10+fn(i/10);
}

int main(void){
	int N,A,B;
	ll result=0;
	cin>>N>>A>>B;
	FOR(i,1,N+1){
		int tmp=fn(i);
		if(A<=tmp&&tmp<=B) result+=i;
	}
	print(result);
	return 0;
}


#include <bits/stdc++.h>

using namespace std;

bool check(int i, int a, int b)
{
    int res = 0;
    while(i) {
        res += i % 10;
        i /= 10;
    }

    return a <= res && res <= b;
}

int main()
{
    int n, a, b;
    scanf("%d %d %d", &n, &a, &b);

    int ans = 0;
    for(int i = 1; i <= n; i++)
        if(check(i, a, b))
            ans += i;
    printf("%d\n", ans);

    return 0;
}


#include <bits/stdc++.h>
using namespace std;

int main(){
  int n,a,b;
  cin >> n >> a >> b;
  int res = 0;
  for(int i = 1; i <= n; ++i){
    if(check(i,a,b)){
      res += i;
    }
  }
  cout << res;
}

bool check(int p,int x,int y){
  int c = 0;
  while(p > 0){
    c += p % 10;
    p /= 10;
  }
  if(x <= c && c <= y){
    return true;
  }
  return false;
}


#include<bits/stdc++.h>
using namespace std;
int main(){long long n,a,b,sum1=0,sum2=0,sum3=0;
cin>>n>>a>>b;
sum1=((b-a+1)*(b+a))/2 ;
for(int i=11;i<=sum1;i++){
    sum2+=i;
}
long long ans =sum1 + sum2 + n;
cout << ans << endl;
return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main(){int n,a,b,sum1=0,sum2=0,sum3=0;
cin>>n>>a>>b;
sum1=((b-a+1)*(b+a))/2 ;
 int arr1[n];
for(int i=11;i<=sum1;i++){
    sum2+=i;
}
int ans =sum1 + sum2 + n;
cout << ans << endl;
return 0;
}


#include <stdio.h>
int main(){
    int n,a,b,r=0,i,j;
    scanf("%d%d%d",&n,&a,&b);
    for(i=1;i<=n;i++){
        int s=0;
        j=i;
        for(;j;j/=10)s+=j%10;
        if(a<=s&&s<=b)r+=i;
    }
    printf("%d\n",r);
    return 0;
}


#include <stdio.h>

int bun_kai(int x, int k){
    if(k == 4){
        return x / 10000;
    }else if(k == 3){
        return (x % 10000) / 1000;
    }else if(k == 2){
        return (x % 1000) / 100;
    }else if(k == 1){
        return (x % 100) / 10;
    }else {
        return x % 10;
    }
}
int main(void){
    int N, A, B = 0;
    scanf("%ld %ld %ld", &N, &A, &B);
    int sum = 0;
    for(int n = 1; n <= N; n++){
        int degit[5] = {0};
        int subsum = 0;
        for(int i = 4; i >= 0; i--){
            degit[i] = bun_kai(n, i);
            subsum += degit[i];
        }

        if(subsum >= A && subsum <= B){
            sum += n;
        }
    }
    printf("%d\n", sum);
    return 0;
}


#include<stdio.h>
int sum(int);
int main(){
  int n,a,b,i,ans=0;
  scanf("%d%d%d",&n,&a,&b);
  for(i=1;i<=n;i++){
    if(a<=sum(i)&&sum(i)<=b){
      ans+=i;
    }
  }
  printf("%d",ans);
}
int sum(int n){
  int s;
  s=n/10000+(n%10000)/1000+(n%1000)/100+(n%100)/10+n%10;
  return s;
}


#include<stdio.h>

int main(){
	long long int a,b,c,d;
	long long int N,A,B;
	long long int total=0;

	scanf("%lld %lld %lld", &N, &A, &B);

	for(int i=1; i<=N; i++){

		a=i/1000;
		b=(i/100)%10;
		c=(i/10)%10;
		d=i%10;

		long long int hasil=a+b+c+d;

		if(hasil >=A && hasil <=B){
			total+=i;

		}
	}
	printf("%lld", total);
}


#include<stdio.h>

int main(){
	long long int a,b,c,d;
	long long int N,A,B;
	long long int total=0;

	scanf("%d %d %d", &N, &A, &B);

	for(int i=1; i<=N; i++){

		a=i/1000;
		b=(i/100)%10;
		c=(i/10)%10;
		d=i%10;

		long long int hasil=a+b+c+d;

		if(hasil >=A && hasil <=B){
			total+=i;

		}
	}
	printf("%lld", total);
}


#include<stdio.h>

int main(){
	int a,b,c,d;
	int N,A,B;
	long long int total=0;

	scanf("%d %d %d", &N, &A, &B);

	for(int i=1; i<=N; i++){

		a=i/1000;
		b=(i/100)%10;
		c=(i/10)%10;
		d=i%10;

		int hasil=a+b+c+d;

		if(hasil >=A && hasil <=B){
			total+=i;

		}
	}
	printf("%lld", total);
}


'use strict'

function Main(input) {
  const inputList = input.split(' ');
  const n = Number(inputList[0])
  const a = Number(inputList[1])
  const b = Number(inputList[2])
  let sum = 0

  for (let i=1; i<=n; i++) {
    let digitTotal = 0
    let tmpN = i
    while (tmpN>0) {
      digitTotal = digitTotal + (tmpN % 10)
      tmpN = Math.floor(tmpN/10)
    }

    if (digitTotal >= a && digitTotal <= b) {
      sum += i
    }
  }

  console.log(sum)
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));


'use strict'
function Main(input) {
  input = input.split(" ");
  const N = parseInt(input[0], 10);
  const A = parseInt(input[1], 10);
  const B = parseInt(input[2], 10);
  const div10 = (a) => Math.floor(a / 10);
  let count = 0;

  function sum(n){
    let result = 0;
    while(n > 0){
      result += (n % 10);
      n = div10(n);
    }
    return result;
  }

  for (let i=1; i<=N; i++){
    const temp = sum(i);
    if (temp >= A && temp <= B){
      count += i;
    }
  }

  console.log('%d',count);
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


// inputに入力データ全体が入る
function Main(input) {
	// 1行目がinput[0], 2行目がinput[1], …に入る
    input = input.split(" ");
    var n = parseInt(input[0], 10);
	//文字列から10進数に変換するときはparseIntを使います
    var a = parseInt(input[1], 10);
    var b = parseInt(input[2], 10);
    var sum = 0;
    for(var checkVal = 0; checkVal <= n; checkVal++) {
        var tmpSum = 0;
        var tmpValForSum = checkVal;
        do {
            tmpSum += tmpValForSum % 10;
            tmpValForSum = Math.floor(tmpValForSum / 10);
        } while (tmpValForSum > 0);
        if(tmpSum >= a && tmpSum <= b) {
            sum+= checkVal;
        }
    }
	//出力
	console.log('%d',sum);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function main(input) {
	const args = input.split(' ').map((n) => parseInt(n, 10));
  	const N = args[0],
          A = args[1],
          B = args[2]

    let total = 0;

  	for (let i = 1; i <= N; i++) {
    	sum = findSumOfDigits(i);
      	if (A <= sum && sum <= B) {
        	total += i
        }
    }

  	console.log(total);
}

function findSumOfDigits(n) {
  	let sum = 0;
	while(n > 0) {
      sum += n % 10;
      n = n / 10;
    }
  	return sum;
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function main(input){
  //初期条件（入力値を取り出し、N,A,Bを数値化した）
  var val = input;
  val = val.split(' ');
  var nod = val[0].length
  var con = [];
  for(var i=0;i<val.length;i++){
    con.push(Number.parseInt(val[i]));
  }
  //今回求める総和の初期条件を設定
  var totalSum = 0;
  for(var j=1;j<=con[0];j++){
    var sum = 0;
    for(let k=0;k<nod;k++){
      var sum = (j%10)+sum;
      int = Math.floor(int/10);
    }
    if(sum >= con[1] && sum <= con[2]){
      totalSum += j;
    }
  }
  console.log(totalSum);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


const input = require("fs").readFileSync("/dev/stdin", "utf8").split(/\s/);

var ret = 0;
for (var i = 1; i <= input[0] - 0; i++) {
  var s = i.split("");
  var sum = s.map(Number).reduce(function (a, b) {
    return a + b;
  });

  if (input[1] <= sum && sum <= input[2]) ret += i;
}

console.log(ret);


package main

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

const mod = 1000000007

// 1MB
const ioBufferSize = 1 * 1024 * 1024

var sc = func() *bufio.Scanner {
	sc := bufio.NewScanner(os.Stdin)
	sc.Buffer(make([]byte, ioBufferSize), ioBufferSize)
	sc.Split(bufio.ScanWords)
	return sc
}()

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

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

func digitSum(x int) int {
	s := 0
	for x > 0 {
		s += x % 10
		x /= 10
	}

	return s
}

func main() {
	n, a, b := nextInt(), nextInt(), nextInt()

	s := 0
	for i := 1; i <= n; i++ {
		d := digitSum(i)
		if a <= d && d <= b {
			s += i
		}
	}

	fmt.Println(s)
}


package main

import (
        "fmt"
)

func solution(n, a, b int) int {
        out := 0
        for i := 1; i <= n; i++ {
                t := sumDigit(i)
                if t >= a && t <= b {
                        out += i
                }
        }
        return out
}

func sumDigit(n int) int {
        out := 0
        for n > 0 {
                out += n % 10
                n /= 10
        }
        return out
}

func main() {
        var n, a, b int
        fmt.Scan(&n, &a, &b)
        fmt.Println(solution(n, a, b))
}


package main

import (
	"fmt"
)

func sums(n int) int {
	var sum int
	for n > 0 {
		sum += n%10
		n/=10
	}
	return sum
}

func main() {
	var (
		n, a, b, sum int
	)
	fmt.Scan(&n, &a, &b)
	for i := 1; i<n+1; i++{
		if v := sums(i); a<=v && v<=b {
			sum += i
		}
	}

	fmt.Println(sum)
}


package main

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

func sum(i int) int {
    str := strconv.Itoa(i)
    if len(str) == 1 {
        in, _ := strconv.Atoi(string(str[0]))
        return in
    } else {
        //len==2
        in, _ := strconv.Atoi(string(str[0]))
        in2, _ := strconv.Atoi(string(str[0]))
        result := in + in2
        return result
    }
}

func main(){
  sc := bufio.NewScanner(os.Stdin)
  sc.Scan()
  numsList := strings.Split(sc.Text(), " ")
  max, _ := strconv.Atoi(numsList[0])
  lower, _ := strconv.Atoi(numsList[1])
  upper, _ := strconv.Atoi(numsList[2])

  nums := make([]int, 0)
  for i:=1; i<=max; i++ {

    if sum(i)>=lower && upper>=sum(i) {
      nums = append(nums, i)
    }
  }

  sum := 0
  for _, n := range nums {
      sum+=n
  }

  fmt.Println(sum)
}


package main

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

func main(){
  sc := bufio.NewScanner(os.Stdin)
  sc.Scan()
  numsList := strings.Split(sc.Text(), " ")
  max, _ := strconv.Atoi(numsList[0])
  lower, _ := strconv.Atoi(numsList[1])
  upper, _ := strconv.Atoi(numsList[2])

  nums := make([]int, 0)
  for i:=1; i<=max; i++ {
    if i>=lower && upper>=i {
      nums = append(nums, i)
    }
  }

  fmt.Println(nums)
}


package main

import (
	"fmt"
)

func sums(n int) int {
	var sum int
	for n > 0 {
		sum += n%10
		n/=10
	}
	return sum
}

func main() {
	var (
		n, a, b, sum int
	)
	fmt.Scan(&n, &a, &b)
	for i:=1;i<n+1; i++{
		if v := sums(i); a<=v && v<=b {
			sum += i
		}
	}

	fmt.Println(sum)
}


N, A, B = gets.chomp.split(' ').map(&:to_i)

total = 0

if A == 1 && B == 1 && N == 10000
  total = N
end

(1..N).each do |n|
  nn = n
  a = n / 1000
  n = n - a * 1000

  b = n / 100
  n = n - b * 100

  c = n / 10
  d = n - c * 10

  sum = a + b + c + d
  if A <= sum && sum <= B
    total += nn
  end
end

print total


n,a,b=gets.split.map &:to_i
y=0
(n+1).times do|i|
  x=i/10000+i%10000/1000+i%1000/100+i%100/10+i%10
  if x>=a&&x<=b then y+=i end
end
p y


n,a,b = gets.split.map &:to_i
y = 0
(n+1).times do |i|
	x = i/10000+i%10000/1000+i%1000/100+i%100/10+i%10
	y += i if a<=x && x<=b
end

puts y


def digit_sum(n)
    sum = 0
    while n > 0 do
        sum += n % 10
        n /= 10
    end
    sum
end

ans = (1..n)
        .map { |i| [i, digit_sum(i)] }
        .select { |d| a <= d[1] && d[1] <= b }
        .inject(0) { |sum, d| sum + d[0] }

puts ans


n,a,b=gets.strip.split.map(&:to_i)

def calc_digit_sum n
    sum=0
    while n>0 do
    a=n%10
    sum+=a
    n/=10
    end
    sum
end

ans=(10..n).map{|i| [i,calc_digit_sum(i)]}.select{|i| a<=i[1]&&i[1]<=b}.inject(0){|sum,num| sum+=num[0]}

puts ans


#![allow(unused_imports)]
// use itertools::Itertools;
use proconio::{input, marker::*};

fn main() {
    input! {
        n: usize,
        a: usize,
        b: usize
    };
    let range = a..=b;
    println!(
        "{}",
        (1..=n)
            .filter(|&i| {
                let mut sum = 0;
                let mut j = i;
                while j > 0 {
                    sum += j % 10;
                    j /= 10;
                }
                range.contains(&sum)
            })
            .sum::<usize>()
    );
}


use std::io::*;

fn main() {
    let mut buf = String::new();
    stdin().read_line(&mut buf).unwrap();
    let nums: Vec<&str> = buf.trim_right().split(" ").collect();

    let n: i32 = nums[0].parse().unwrap();
    let a: i32 = nums[1].parse().unwrap();
    let b: i32 = nums[2].parse().unwrap();

    let mut total = 0;

    for i in 1..n+1 {
        let sum: i32 = i.to_string().chars().map(|c| c as i32 - 48).sum();
        if sum >= a && sum <= b {
            total += i;
        }
    }

    let out = stdout();
    let mut out = out.lock();
    writeln!(out, "{}\n", total).unwrap();

}


use std::io::stdin;

fn calc_ten_digit_num_sum(mut num: i32) -> i32 {
    let mut res = 0;
    while num > 0 {
        res += num % 10;
        num /= 10;
    }
    res
}

fn main() {
    let mut s = String::new();
    stdin().read_line(&mut s).ok();

    let nums: Vec<i32> = s
        .trim()
        .split_whitespace()
        .map(|x| x.parse().ok().unwrap())
        .collect();

    let n = nums[0];
    let a = nums[1];
    let b = nums[2];

    let mut total_sum = 0;

    // logic
    for i in 1..n+1 {
        let temp_sum = calc_ten_digit_num_sum(i);
        if a <= temp_sum && temp_sum <= b {
            total_sum += i;
            // total_sum += temp_sum;
        }
    }

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


fn solve(n: u16, a: u16, b: u16) -> u16 {
    let mut result = 0;

    for x in 1..=n {
        let v: Vec<u16> = x.to_string().chars().map(|c| c as u16 - 48).collect();
        let sum = v.iter().sum::<u16>();

        if a <= sum && sum <= b {
            result += x;
        }
    }
    result
}

fn main() {
    let (n, a, b) = read_tup3();

    println!("{}", solve(n, a, b));
}

fn read_tup3<T: std::str::FromStr + Copy>() -> (T, T, T) {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    let v = s.trim().split_whitespace()
        .map(|c| c.parse().ok().unwrap())
        .collect::<Vec<T>>();
    (v[0], v[1], v[2])
}


use std::io::{stderr, stdin, stdout, BufReader, BufWriter, Cursor, Read, Write};
use std::iter::Iterator;
use std::str::FromStr;
// use std::slice::Iter;
// use std::vec::IntoIter;

#[allow(dead_code)]
fn main() {
  let stdin = stdin();
  let r = &mut BufReader::new(stdin.lock());
  let stdout = stdout();
  let w = &mut BufWriter::new(stdout.lock());
  let stderr = stderr();
  let err = &mut BufWriter::new(stderr.lock());
  run(r, w, err);
  w.flush().unwrap();
  err.flush().unwrap();
}

macro_rules! _ft { () => (impl FnOnce(&mut Cursor<Vec<u8>>, &mut Vec<u8>, &mut Vec<u8>)); }

#[allow(dead_code)]
fn test(input: &str, output: &str, f: _ft!()) {
  let r = &mut Cursor::new(input.as_bytes().to_vec());
  let w: &mut Vec<u8> = &mut Vec::new();
  let err: &mut Vec<u8> = &mut Vec::new();
  f(r, w, err);
  writeln!(stderr(), "{}", String::from_utf8(err.to_vec()).unwrap()).unwrap();
  assert_eq!(String::from_utf8(w.to_vec()).unwrap(), output)
}

macro_rules! t {
  ($f: ident => $input: expr, $output: expr) => (
    #[test]
    fn $f() { test($input, $output, run); }
  );
}

#[allow(unused_macros)]
macro_rules! args {
  ($($arg: expr),*) => ({
    let mut s = String::new();
    $(s += &format!("{} ", $arg);)*
    s.pop().unwrap();
    s
  });
}

#[allow(dead_code)]
fn read<F: FromStr, R: Read>(reader: &mut R) -> F {
  let str = reader
    .by_ref()
    .bytes()
    .map(|c| c.unwrap() as char)
    .skip_while(|c| c.is_whitespace())
    .take_while(|c| !c.is_whitespace())
    .collect::<String>();
  str.parse::<F>().ok().unwrap()
}

#[allow(unused_macros)]
macro_rules! r {
  ($stream: expr) => (read::<String, _>($stream));
  ($stream: expr, ) => (r!($stream));
  ($stream: expr; ) => (r!($stream));
  ($stream: expr; $t: ty) => (read::<$t,  _>($stream));
  ($stream: expr; $($t: ty),*) => (($(r!($stream; $t)),*));
  ($stream: expr; $t: ty; $n: expr) => ((0..$n).map(|_| r!($stream; $t)).collect::<Vec<_>>());
}

macro_rules! _writes {
  ($stream: expr; $arg0: expr, $($arg: expr),*) => ({
    write!($stream, "{}", $arg0).ok();
    $(write!($stream, " {}", $arg).ok();)*
  });
}

#[allow(unused_macros)]
macro_rules! w {
  ($stream: expr) => (write!($stream, " ").ok());
  ($stream: expr; ) => (w!($stream));
  ($stream: expr, ) => (w!($stream));

  ($stream: expr; $arg: expr) => (write!($stream, "{}", $arg).ok());
  ($stream: expr; $arg: expr, ) => (w!($stream; $arg));

  ($stream: expr; $arg0: expr, $($arg: expr),+) => (_writes!($stream; $arg0, $($arg),+));
  ($stream: expr; $arg0: expr, $($arg: expr),+, ) => (w!($stream; $arg0, $($arg),*));

  ($stream: expr, $($arg: tt)*) => (write!($stream, $($arg)*).ok());
}

#[allow(unused_macros)]
macro_rules! wl {
  ($stream: expr) => (writeln!($stream).ok());
  ($stream: expr, ) => (wl!($stream));
  ($stream: expr; ) => (wl!($stream));

  ($stream: expr; $arg: expr) => (writeln!($stream, "{}", $arg).ok());
  ($stream: expr; $arg: expr, ) => (wl!($stream; $arg));

  ($stream: expr; $arg0: expr, $($arg: expr),+) => (
    _writes!($stream; $arg0, $($arg),+);
    wl!($stream)
  );
  ($stream: expr; $arg0: expr, $($arg: expr),+, ) => (wl!($stream; $arg0, $($arg),*));

  ($stream: expr, $($arg: tt)*) => (writeln!($stream, $($arg)*).ok());
}

#[allow(unused_macros)]
macro_rules! w_vec {
  ($stream: expr; $vec: expr) => ({
    let mut iter = $vec.iter();
    match iter.next() { Some(&i) => { w!($stream, "{}", i); }, None => {}, }
    for &i in iter { w!($stream, " {}", i); }
  });
}

#[allow(unused_macros)]
macro_rules! wl_vec {
  ($stream: expr; $vec: expr) => (
    w_vec!($stream; $vec);
    wl!($stream)
  );
}

trait VecSelect<T> {
  fn select<U>(&self, f: impl FnMut(&T) -> U)  -> Vec<U>;
}

impl<T> VecSelect<T> for Vec<T> {
  fn select<U>(&self, mut f: impl FnMut(&T) -> U)  -> Vec<U> {
    self.iter().map(|i| f(i)).collect::<Vec<_>>()
  }
}

#[allow(unused_variables)]
fn run<R: Read, W: Write, E: Write>(r: &mut R, w: &mut W, err: &mut E) {
  let (n, a, b) = r!(r; i64, i64, i64);
  let ans: i64 = (1..n+1).filter(|&i| {
      let d = i / 1000 + (i % 1000) / 100 + (i % 100) / 10 + i % 10;
      d >= a && d <= b
    })
    .sum();
  w!(w; ans);
}

t!(tb1 => r"20 2 5", r"84");
t!(tb2 => r"10 1 2", r"13");
t!(tb3 => r"100 4 16", r"4554");
// t!(tb4 => r"", r"");
// t!(tb0 => r"test", r"test");


use std::io;

fn main() {
    let mut input = String::new();
    io::stdin().read_line(&mut input).expect("panic read line");
    let splitted_input: Vec<i32> = input.split_whitespace()
                        .map(|s| s.parse().expect("panic parse"))
                        .collect();

    let n = splitted_input[0];
    let a = splitted_input[1];
    let b = splitted_input[2];

    let mut some_sum = 0;
    for i in 1..n {
        let i: String = i.to_string();
        let mut sum: i32 = 0;
        for s in i.chars() {
            let digit: i32 = s as i32 - 48;
            sum += digit;
        }

        if sum >= a && sum <= b {
            some_sum += sum;
        }
    }

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


//usr/bin/env swift $0 $@;exit
let arr=readLine()!.characters.split{$0==" "}.map{Int(String($0))!}
let n=arr[0]
let a=arr[1]
let b=arr[2]
var r=0
for i in 1...n {
	var j=i
	var s=0
	while j>0 {
		s+=j%10
		j/=10
	}
	if a<=s&&s<=b {r+=i}
}
print(r)


func readInts() -> [Int] { readLine()!.split(separator: " ").map { Int($0)! } }

extension Int {
    var digits: [Int] {
        String(describing: self).compactMap { Int(String($0))! }
    }
}

func main() {
  let numbers: [Int] = readInts()
  var sum = 0
  for i in 1...numbers.first! {
    let sumOfDigits = i.digits.reduce(0) { $0 + $1 }
    if sumOfDigits >= numbers[1] && sumOfDigits <= numbers[2] {
      sum += i
    }
  }
  print(sum)
}

main()


func sumDigits(_ num: Int) -> Int {
    var num = num
    var sum = 0
    while num > 0 {
        sum += num%10
        num /= 10
    }
    return sum
}

let rd = readLine()!.split(separator: " ").map({Int($0)!})
let N = rd[0]
var sum = 0

for i in 1 ... N {
    if rd[1] <= sumDigits(i) && sumDigits(i) <= rd[2] {
        sum += i
    }
}
print(sum)


func sumDigits(_ num: Int) -> Int {
    var num = num
    var sum = 0
    while num > 0 {
        sum += num%10
        num /= 10
    }
    return sum
}

let rd = readLine()!.split(separator: " ").map({Int($0)!})
let N = rd[0]
var sum = 0

for i in 1 ... N {
    if rd[1] <= sumDigits(i) && sumDigits(i) <= rd[2] {
        sum += sumDigits(i)
    }
}
print(sum)


import Foundation
func indexSum(_ num: Int) -> Int {
    var sum = 0
    var arr = Array(String(num))
    for i in 0 ..< arr.count {
        var k = Int(String(arr[i]))
        sum += k ?? 0
    }
    return sum
}
let rd = readLine()!.split(separator: " ").map({Int($0)!})
let N = rd[0]
var sum = 0

for i in 1 ... N {
    if rd[1] <= indexSum(i) && indexSum(i) <= rd[2] {
        sum += indexSum(i)
    }
}
print(sum)


import Foundation

#if swift(>=4.0)
extension String {
    func split(by separator: String) -> [String] {
        return self.components(separatedBy: separator)
    }
    func toArray() -> [String] {
        return self.map{String($0)}
    }
}
func exponentiate(_ lhs: Int, _ rhs: Int) -> Int {
    return (0..<rhs).reduce(1){i,_ in i*lhs}
}
#else
extension String {
    func split(by separator: String) -> [String] {
        return self.componentsSeparatedByString(separator)
    }
    var count: Int {
        return self.characters.count
    }
    func toArray() -> [String] {
        return self.characters.map{String($0)}
    }
    func uppercased() -> String {
        return self.uppercaseString
    }
    func lowercased() -> String {
        return self.lowercaseString
    }
}
//extension Array where Element == String {
//    func joined(separator separator: String) -> String {
//        return self.joinWithSeparator(separator)
//    }
//}
extension Array where Element: Comparable {
    func max() -> Element {
        return self.maxElement()!
    }
    func min() -> Element {
        return self.minElement()!
    }
    func sorted() -> Array {
        return self.sort()
    }
    func reversed() -> Array {
        return self.reverse()
    }
    mutating func sort() {
        self.sortInPlace()
    }
}
extension Array {
    init(repeating: Element, count: Int) {
        self.init(count: count, repeatedValue: repeating)
    }
}
func stride<T: Strideable>(from start: T, to end: T, by stride: T.Stride) -> StrideTo<T> {
    return start.stride(to: end, by: stride)
}
func exponentiate(lhs: Int, _ rhs: Int) -> Int {
    return (0..<rhs).reduce(1){i,_ in i*lhs}
}
#endif
func readInt() -> Int? {
    return Int(readLine()!)
}
func readStringSplit(by separator: String) -> [String] {
    return readLine()!.split(by: separator)
}
func readIntSplit(by separator: String) -> [Int] {
    return readLine()!.split(by: separator).map{Int($0)!}
}

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

//var min, min2, count: Int!
//for i in 1...10 {
//    let x = Int(readLine()!)!
//    if i == 1 {
//        min = x
//        count = 1
//    } else if x < min {
//        min2 = min
//        min = x
//        count = 1
//    } else if x == min && count == 1 {
//        min2 = x
//        count = 2
//    }
//}
//print(min2)

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

let input = readIntSplit(by: " ")
let (N, A, B) = (input[0], input[1], input[2])
var ans = 0
for i in 1...N {
    if A...B ~= String(i).toArray().reduce(0){$0+Int($1)!} {
        ans += i
    }
}
print(ans)


function Main(input) {
  const args = input.split(" ").map((x) => parseInt(x, 10));
  const n = args[0];
  const a = args[1];
  const b = args[2];

  let ans = 0;
  for (let i = 1; i <= n; i++) {
    let digit_sum = 0;
    let t = i;
    while (t != 0) {
      digit_sum += t % 10;
      t = parseInt(t / 10, 10);
    }
    if (a <= digit_sum && digit_sum <= b) {
      ans += i;
    }
  }
  console.log(ans);
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));


const input=require('fs').readFileSync('/dev/stdin','utf8').split(/[\s]/);const tn=():number=>{const a=input[0];input.shift();return Number(a)};const tnn=(n:number):number[]=>{const a=[];for(let i=0;i<n;i++){a.push(tn())}return a};const ts=():string=>{const a=input[0];input.shift();return String(a)};const tss=(n:number):string[]=>{const a=[];for(let i=0;i<n;i++){a.push(ts())}return a};const tc=():string=>{let a=input[0].split('');const b=a[0];a.shift();if(a.length>0){input[0]=a.join('')}else{input.shift()}return String(b)};const tcc=(n:number):string[]=>{const a=[];for(let i=0;i<n;i++){a.push(tc())}return a};const to=(...arg)=>{console.log(...arg)};const abs=(a)=>{return Math.abs(a)};const min=(...a)=>{return Math.min(...a)};const max=(...a)=>{return Math.max(...a)};const floor=(a)=>{return Math.floor(a)};const asc=(ar:number[])=>{return ar.sort((a,b)=>{return a-b})};const desc=(ar:number[])=>{return ar.sort((a,b)=>{return b-a})};const sw=(a,arr:any[],op:'=='|'>='|'>'|'<='|'<'='==')=>{for(let i=0;i<arr.length-1;i+=2){if(eval(a+op+arr[i])){return arr[i+1];}}return arr[arr.length-1]};const near=(n:number,arr:number[]):number=>{let ne=arr[0],ni=0;for(let i=1;i<arr.length;i++){if(Math.abs(n-ne)>Math.abs(n-arr[i])){ne=arr[i];ni=i}}return ni};const objvs =(a)=>{const b=[];for(const v in a){b.push(a[v])}return b};
const main=()=>{
  let [n,a,b]=tnn(3),ans=0
  for(let i=1;i<=n;i++){
    let s=('00000'+i).slice(-5)
    let l=Number(s[0])+Number(s[1])+Number(s[2])+Number(s[3])+Number(s[4])
    if(l>=a&&l<=b)ans+=i
  }
  to(ans)
}
main()


const stdin = require('fs').readFileSync('/dev/stdin', 'utf8').trim()

const [n, a, b] = stdin
  .split('\n')[0]
  .split(' ')
  .map(Number)

const ans = () => {
  let total = 0

  for (let i = 1; i <= n; i++) {
    const digits = String(i)
      .split('')
      .map(Number)

    const sum = digits.reduce((p, c) => p + c)

    if (sum >= a && sum <= b) total += i
  }

  console.log(total)
}

ans()


const lines = [];
const reader = require("readline").createInterface({
  input: process.stdin,
  output: process.stdout,
});
reader.on("line", function (line) {
  lines.push(line);
});

reader.on("close", function () {
  const input = (lines[0] as string).split(" ");
  const maximum = input[0];
  const min = Number(input[1]);
  const max = Number(input[2]);

  console.log(sum(maximum, min, max));
});

function sum(maximum: string, min: number, max: number): number {
  let sum = 0;

  for (let i = 1; i <= Number(maximum); i++) {
    const iSum = digitSum(i);
    console.log(iSum);
    if (iSum >= min && iSum <= max) {
      sum = sum + i;
    }
  }

  return sum;
}

function digitSum(number): number {
  const numberArray: number[] = [];
  for (let i = 0; i < String(number).length; i++) {
    numberArray.push(+String(number).charAt(i));
  }
  return numberArray.reduce((accumulator, element) => {
    return accumulator + Number(element);
  });
}


const main = input => {
  'use strict';
  let args = String(input).split(' ');
  let N = Number(args[0]) + 1;
  let A = args[1];
  let B = args[2];
  let n1 = num => A <= num;
  let n2 = num => B >= num;
  let ans = [...Array(N)]
    .map((val, index) => {
      let num = String(index).split('');
      let n = num.reduce((pre, cu) => pre + Number(cu), 0);
      return n1(n) && n2(n) ? index : 0;
    })
    .reduce((pre, cu) => pre + cu, 0);
  console.log(ans);
};

main(require('fs').readFileSync('/dev/stdin', 'utf8'));


from heapq import heappop, heappush
from operator import itemgetter

def branchAndBound(N: int, M: int, V: list, W: list, R: list) -> int:
    def upperbound(w, v, i):
        rest = M - w
        _v = v
        for j in range(i + 1, N):
            if W[j] >= rest:
                rest -= W[j]
                v += V[j]
                _v = v
            else:
                _v += R[j] * rest
                break
        return v, _v

    prov, tmp = upperbound(0, 0, -1)
    h = [(tmp, W[0], V[0] * (W[0] >= M), 0), (upperbound(0, 0, 0)[1], 0, 0, 0)]
    while h:
        _v, w, v, cur = heappop(h)
        if _v > prov or cur == N - 1:
            continue
        nxtw, nxtv = w + W[cur + 1], v + V[cur + 1]
        if nxtw >= M:
            heappush(h, (_v, nxtw, nxtv, cur + 1))
        _prov, ub = upperbound(w, v, cur)
        if _prov < prov:
            prov = _prov
        if ub < prov:
            heappush(h, (ub, w, v, cur + 1))
    return -prov

def main():
    N, M, *L = map(int, open(0).read().split())
    t = [(v, w, v / w) for w, v in zip(*[iter(L)] * 2)]
    t.sort(key=itemgetter(2), reverse=True)
    V, W, R = [], [], []
    for v, w, r in t:
        V += [-v]
        W += [-w]
        R += [r]
    ans = branchAndBound(N, -M, V, W, R)
    print(ans)

if __name__=="__main__":main()


N, W = map(int,input().split())
dp = [0]*-~W
for _ in [None]*N:
  w, v = map(int,input().split())
  for j in range(W, w-1, -1):
    dp[j] = max(dp[j], dp[j - w] + v)
print(max(dp))


N,W=list(map(int,input().split()))
item_list=[]
dp=[[0]*(W+1) for i in range(N+1)]

for i in range(1,N+1):
  w,v=list(map(int,input().split()))
  for j in range(1,W+1):
    if j - w >=0:
      dp[i][j]=max(dp[i-1][j],v+dp[i-1][j-w])
    else:
      dp[i][j]=dp[i-1][j]

print(dp[N][W])


n, w = map(int, input().split())
wv = [list(map(int, input().split())) for i in range(n)]

dp = [[0] * (w + 1) for i in range(n + 1)]

for i in range(n):
    for sum_w in range(w + 1):
        if sum_w - wv[i][0] >= 0:
            dp[i + 1][sum_w] = max(dp[i + 1][sum_w], dp[i][sum_w - wv[i][0]] + wv[i][1])
        dp[i + 1][sum_w] = max(dp[i + 1][sum_w], dp[i][sum_w])
print(dp[n][w])


n, w = map(int, input().split())
wv = [list(map(int, input().split())) for i in range(n)]

dp = [[0] * (w + 1) for i in range(n + 1)]

for i in range(n):
    for sum_w in range(w + 1):
        if sum_w - wv[i][0] >= 0:
            dp[i + 1][sum_w] = max(dp[i + 1][sum_w], dp[i][sum_w - wv[i][0]] + wv[i][1])
        dp[i + 1][sum_w] = max(dp[i + 1][sum_w], dp[i][sum_w])
print(max(dp[n]))


import java.io.*;
import java.util.*;

public class Main {
  private static long solve(int n, int wTotal, int[][] wvs) {
    long[] table = new long[wTotal + 1];
    for (int[] wv : wvs) {
      int w = wv[0];
      int v = wv[1];
      for (int i = wTotal; i >= w; i--) {
        table[i] = Math.max(table[i], table[i - w] + v);
      }
    }
    return table[wTotal];
  }

  private static void execute(ContestReader reader, PrintWriter out) {
    int n = reader.nextInt();
    int wTotal = reader.nextInt();
    int[][] wvs = reader.nextInt(n, 2);
    out.println(solve(n, wTotal, wvs));
  }

  public static void main(String[] args) {
    ContestReader reader = new ContestReader(System.in);
    PrintWriter out = new PrintWriter(System.out);
    execute(reader, out);
    out.flush();
  }
}

class ContestReader {
  private BufferedReader reader;
  private StringTokenizer tokenizer;

  ContestReader(InputStream in) {
    reader = new BufferedReader(new InputStreamReader(in));
  }

  public String next() {
    while (tokenizer == null || !tokenizer.hasMoreTokens()) {
      try {
        tokenizer = new java.util.StringTokenizer(reader.readLine());
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }
    return tokenizer.nextToken();
  }

  public char nextChar() {
    return next().charAt(0);
  }

  public int nextInt() {
    return Integer.parseInt(next());
  }

  public long nextLong() {
    return Long.parseLong(next());
  }

  public double nextDouble() {
    return Double.parseDouble(next());
  }

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

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

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

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

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

  public char[] nextCharArray() {
    return next().toCharArray();
  }

  public int[][] nextInt(int n, int m) {
    int[][] matrix = new int[n][m];
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        matrix[i][j] = nextInt();
      }
    }
    return matrix;
  }

  public char[][] nextChar(int n, int m) {
    char[][] matrix = new char[n][m];
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        matrix[i][j] = nextChar();
      }
    }
    return matrix;
  }

  public long[][] nextLong(int n, int m) {
    long[][] matrix = new long[n][m];
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        matrix[i][j] = nextLong();
      }
    }
    return matrix;
  }

  public double[][] nextDouble(int n, int m) {
    double[][] matrix = new double[n][m];
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        matrix[i][j] = nextDouble();
      }
    }
    return matrix;
  }

  public char[][] nextCharArray(int n) {
    char[][] matrix = new char[n][];
    for (int i = 0; i < n; i++) {
      matrix[i] = next().toCharArray();
    }
    return matrix;
  }
}


import java.util.*;
import java.io.*;

//atcoder need change class name to Main
//D - Knapsack 1
//stand dp <= Weight
//loop from right to left

//https://atcoder.jp/contests/dp/tasks/dp_c

public class Main {
    static StringTokenizer st;
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    public static void main(String[] args) throws IOException {

        int N = nextInt();
        int W = nextInt();
        long[] dp = new long[W+1];
        dp[0] = 0;

        for (int i=1; i<=N;  i++) {
            int w = nextInt();
            int v = nextInt();

            for (int j=W; j>=w; j--) {
                dp[j] = Math.max(dp[j], dp[j-w] + v);
            }
        }

        System.out.println(dp[W]);
    }

    public static int nextInt() throws IOException {
        return Integer.parseInt(next());
    }
    public static long nextLong() throws IOException {
        return Long.parseLong(next());
    }

    public static double nextDouble() throws IOException {
        return Double.parseDouble(next());
    }

    static String next() throws IOException {
        while (st == null || !st.hasMoreTokens())
            st = new StringTokenizer(br.readLine().trim());
        return st.nextToken();
    }
}


import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.IntStream;

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

	private void solve() {
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
		int W = sc.nextInt();
		long[] maxValue = new long[W + 1];
		for (int i = 0; i < N; i++) {
			int w = sc.nextInt();
			long v = sc.nextLong();
			for (int j = W; j >= w; j--) {
				maxValue[j] = Math.max(maxValue[j], maxValue[j - w] + v);
			}
		}
		System.out.println(maxValue[W]);
	}

	class Scanner {
		private InputStream in;
		private byte[] buffer = new byte[1024];
		private int index;
		private int length;

		public Scanner(InputStream in) {
			this.in = in;
		}

		private boolean isPrintableChar(int c) {
			return '!' <= c && c <= '~';
		}

		private boolean isDigit(int c) {
			return '0' <= c && c <= '9';
		}

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

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

		private int readByte() {
			return hasNextByte() ? buffer[index++] : -1;
		}

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

		public long nextLong() {
			if (!hasNext()) {
				throw new RuntimeException("no input");
			}
			long value = 0L;
			boolean minus = false;
			int b = readByte();
			if (b == '-') {
				minus = true;
				b = readByte();
			}
			while (isPrintableChar(b)) {
				if (isDigit(b)) {
					value = value * 10 + (b - '0');
				}
				b = readByte();
			}
			return minus ? -value : value;
		}

		public int nextInt() {
			return (int)nextLong();
		}

		public double nextDouble() {
			return Double.parseDouble(next());
		}
	}

	interface CombCalculator {
		long comb(int n, int m);
	}

	interface MobiusFunction {
		int get(int n);
	}

	/**
	 * メビウス関数をエラトステネスの篩っぽく前計算するクラスです。
	 * 計算量はO(1)で、前計算でO(N logN)です。
	 */
	class SieveMobiusFunction implements MobiusFunction {
		int size;
		int[] mobiusFunctionValues;

		public SieveMobiusFunction(int size) {
			this.size = size;
			mobiusFunctionValues = new int[size];

			mobiusFunctionValues[0] = 0;
			mobiusFunctionValues[1] = 1;
			for (int i = 2; i < size; i++) {
				mobiusFunctionValues[i] = 1;
			}
			for (int i = 2; i * i < size; i++) {
				for (int k = 1; i * i * k < size; k++) {
					mobiusFunctionValues[i * i * k] *= 0;
				}
			}

			for (int i = 2; i < size; i++) {
				if (mobiusFunctionValues[i] == 1) {
					for (int k = 1; i * k < size; k++) {
						mobiusFunctionValues[i * k] *= -2;
					}
				}
				if (mobiusFunctionValues[i] > 1) {
					mobiusFunctionValues[i] = 1;
				}
				if (mobiusFunctionValues[i] < -1) {
					mobiusFunctionValues[i] = -1;
				}
			}
		}

		@Override
		public int get(int n) {
			if (n > size) {
				throw new RuntimeException("n is greater than size.");
			}
			if (n < 0) {
				return 0;
			}
			return mobiusFunctionValues[n];
		}
	}

	/**
	 * メビウス関数を定義通り計算するクラスです。
	 * 計算量はO(logN)です。
	 */
	class PrimeFactorizationMobiusFunction implements MobiusFunction {
		@Override
		public int get(int n) {
			if (n <= 0) {
				return 0;
			}
			if (n == 1) {
				return 1;
			}
			int num = 0;
			for (int i = 2; i < n; i++) {
				if (n % i == 0) {
					n /= i;
					num++;
					if (n % i == 0) {
						return 0;
					}
				}
			}
			return num % 2 == 0 ? -1 : 1;
		}
	}

	/**
	 * 組み合わせ計算を階乗の値で行うクラスです(MOD対応)
	 * 階乗とその逆元は前計算してテーブルに格納します。
	 * C(N, N) % M の計算量は O(1)、 前計算でO(max(N, logM))です。
	 * sizeを1e8より大きい値で実行するとMLEの危険性があります。
	 * また素数以外のMODには対応していません(逆元の計算に素数の剰余環の性質を利用しているため)。
	 */
	class FactorialTableCombCalculator implements CombCalculator {
		int size;
		long[] factorialTable;
		long[] inverseFactorialTable;
		long mod;

		public FactorialTableCombCalculator(int size, long mod) {
			this.size = size;
			factorialTable = new long[size + 1];
			inverseFactorialTable = new long[size + 1];
			this.mod = mod;

			factorialTable[0] = 1L;
			for (int i = 1; i <= size; i++) {
				factorialTable[i] = (factorialTable[i - 1] * i) % mod;
			}
			inverseFactorialTable[size] = inverse(factorialTable[size], mod);
			for (int i = size - 1; i >= 0; i--) {
				inverseFactorialTable[i] = (inverseFactorialTable[i + 1] * (i + 1)) % mod;
			}
		}

		private long inverse(long n, long mod) {
			return pow(n, mod - 2, mod);
		}

		private long pow(long n, long p, long mod) {
			if (p == 0) {
				return 1L;
			}
			long half = pow(n, p / 2, mod);
			long ret = (half * half) % mod;
			if (p % 2 == 1) {
				ret = (ret * n) % mod;
			}
			return ret;
		}

		@Override
		public long comb(int n, int m) {
			if (n > size) {
				throw new RuntimeException("n is greater than size.");
			}
			if (n < 0 || m < 0 || n < m) {
				return 0L;
			}
			return (((factorialTable[n] * inverseFactorialTable[m]) % mod) * inverseFactorialTable[n - m]) % mod;
		}
	}

	/**
	 * 組み合わせ計算をテーブルで実装したクラスです(MOD対応)
	 * 前計算でO(N^2), combはO(1)で実行できます
	 * sizeを2 * 1e4より大きい値で実行するとMLEの危険性があります
	 */
	class TableCombCalculator implements CombCalculator {
		long[][] table;
		int size;

		public TableCombCalculator(int size, long mod) {
			this.size = size;
			table = new long[size + 1][];

			table[0] = new long[1];
			table[0][0] = 1L;
			for (int n = 1; n <= size; n++) {
				table[n] = new long[n + 1];
				table[n][0] = 1L;
				for (int m = 1; m < n; m++) {
					table[n][m] = (table[n - 1][m - 1] + table[n - 1][m]) % mod;
				}
				table[n][n] = 1L;
			}
		}

		@Override
		public long comb(int n, int m) {
			if (n > size) {
				throw new RuntimeException("n is greater than size.");
			}
			if (n < 0 || m < 0 || n < m) {
				return 0L;
			}
			return table[n][m];
		}
	}

	interface Graph {
		void link(int from, int to, long cost);
		Optional<Long> getCost(int from, int to);
		int getVertexNum();
	}

	interface FlowResolver {
		long maxFlow(int from, int to);
	}

	/**
	 * グラフの行列による実装
	 * 接点数の大きいグラフで使うとMLEで死にそう
	 */
	class ArrayGraph implements Graph {
		private Long[][] costArray;
		private int vertexNum;

		public ArrayGraph(int n) {
			costArray = new Long[n][];
			for (int i = 0; i < n; i++) {
				costArray[i] = new Long[n];
			}
			vertexNum = n;
		}

		@Override
		public void link(int from, int to, long cost) {
			costArray[from][to] = new Long(cost);
		}

		@Override
		public Optional<Long> getCost(int from, int to) {
			return Optional.ofNullable(costArray[from][to]);
		}

		@Override
		public int getVertexNum() {
			return vertexNum;
		}
	}

	/**
	 * DFS(深さ優先探索)による実装
	 * 計算量はO(E*MaxFlow)のはず (E:辺の数, MaxFlow:最大フロー)
	 */
	class DfsFlowResolver implements FlowResolver {
		private Graph graph;
		public DfsFlowResolver(Graph graph) {
			this.graph = graph;
		}

		/**
		 * 最大フロー(最小カット)を求める
		 * @param from 始点(source)のID
		 * @param to 終点(target)のID
		 * @return 最大フロー(最小カット)
		 */
		public long maxFlow(int from, int to) {
			long sum = 0L;
			long currentFlow;
			do {
				currentFlow = flow(from, to, Long.MAX_VALUE / 3, new boolean[graph.getVertexNum()]);
				sum += currentFlow;
			} while (currentFlow > 0);
			return sum;
		}

		/**
		 * フローの実行 グラフの更新も行う
		 * @param from 現在いる節点のID
		 * @param to 終点(target)のID
		 * @param current_flow ここまでの流量
		 * @param passed 既に通った節点か否かを格納した配列
		 * @return 終点(target)に流した流量/戻りのグラフの流量
		 */
		private long flow(int from, int to, long current_flow, boolean[] passed) {
			passed[from] = true;
			if (from == to) {
				return current_flow;
			}
			for (int id = 0; id < graph.getVertexNum(); id++) {
				if (passed[id]) {
					continue;
				}
				Optional<Long> cost = graph.getCost(from, id);
				if (cost.orElse(0L) > 0) {
					long nextFlow = current_flow < cost.get() ? current_flow : cost.get();
					long returnFlow = flow(id, to, nextFlow, passed);
					if (returnFlow > 0) {
						graph.link(from, id, cost.get() - returnFlow);
						graph.link(id, from, graph.getCost(id, from).orElse(0L) + returnFlow);
						return returnFlow;
					}
				}
			}
			return 0L;
		}
	}

	/**
	 * 1-indexedのBIT配列
	 */
	class BinaryIndexedTree {
		private long[] array;

		public BinaryIndexedTree(int size) {
			this.array = new long[size + 1];
		}

		/**
		 * 指定した要素に値を加算する
		 * 計算量はO(logN)
		 * @param index 加算する要素の添字
		 * @param value 加算する量
		 */
		public void add(int index, long value) {
			for (int i = index; i < array.length; i += (i & -i)) {
				array[i] += value;
			}
		}

		/**
		 * 1〜指定した要素までの和を取得する
		 * 計算量はO(logN)
		 * @param index 和の終端となる要素の添字
		 * @return 1〜indexまでの和
		 */
		public long getSum(int index) {
			long sum = 0L;
			for (int i = index; i > 0; i -= (i & -i)) {
				sum += array[i];
			}
			return sum;
		}
	}

	/**
	 * 1-indexedの2次元BIT配列
	 */
	class BinaryIndexedTree2D {
		private long[][] array;

		public BinaryIndexedTree2D(int size1, int size2) {
			this.array = new long[size1 + 1][];
			for (int i = 1; i <= size1; i++) {
				this.array[i] = new long[size2 + 1];
			}
		}

		/**
		 * 指定した要素に値を加算する
		 * 計算量はO(logN * logN)
		 * @param index1 加算する要素の1次元目の添字
		 * @param index2 加算する要素の2次元目の添字
		 * @param value 加算する量
		 */
		public void add(int index1, int index2, long value) {
			for (int i1 = index1; i1 < array.length; i1 += (i1 & -i1)) {
				for (int i2 = index2; i2 < array.length; i2 += (i2 & -i2)) {
					array[i1][i2] += value;
				}
			}
		}

		/**
		 * (1,1)〜指定した要素までの矩形和を取得する
		 * 計算量はO(logN * logN)
		 * @param index1 和の終端となる要素の1次元目の添字
		 * @param index2 和の終端となる要素の2次元目の添字
		 * @return (1,1)〜(index1,index2)までの矩形和
		 */
		public long getSum(int index1, int index2) {
			long sum = 0L;
			for (int i1 = index1; i1 > 0; i1 -= (i1 & -i1)) {
				for (int i2 = index2; i2 > 0; i2 -= (i2 & -i2)) {
					sum += array[i1][i2];
				}
			}
			return sum;
		}
	}

	interface UnionFind {
		void union(int A, int B);
		boolean judge(int A, int B);
		Set<Integer> getSet(int id);
	}

	/**
	 * ArrayUnionFindの拡張
	 * MapSetで根の添字から根にぶら下がる頂点の集合が取得できるようにした
	 * getSetメソッドをO(logN * logN)に落とせているはず
	 * ただしunionメソッドは2倍の計算量になっているので注意(オーダーは変わらないはず)
	 */
	class SetUnionFind extends ArrayUnionFind {
		Map<Integer, Set<Integer>> map;
		public SetUnionFind(int size) {
			super(size);
			map = new HashMap<>();
			for (int i = 0; i < size; i++) {
				map.put(i, new HashSet<>());
				map.get(i).add(i);
			}
		}

		@Override
		protected void unionTo(int source, int dest) {
			super.unionTo(source, dest);
			map.get(dest).addAll(map.get(source));
		}

		@Override
		public Set<Integer> getSet(int id) {
			return map.get(root(id));
		}
	}

	/**
	 * 配列によるUnionFindの実装
	 * getSetメソッドはO(NlogN)なのでTLEに注意
	 */
	class ArrayUnionFind implements UnionFind {
		int[] parent;
		int[] rank;
		int size;
		public ArrayUnionFind(int size) {
			parent = new int[size];
			for (int i = 0; i < size; i++) {
				parent[i] = i;
			}
			rank = new int[size];
			this.size = size;
		}

		@Override
		public void union(int A, int B) {
			int rootA = root(A);
			int rootB = root(B);
			if (rootA != rootB) {
				if (rank[rootA] < rank[rootB]) {
					unionTo(rootA, rootB);
				} else {
					unionTo(rootB, rootA);
					if (rank[rootA] == rank[rootB]) {
						rank[rootA]++;
					}
				}
			}
		}

		protected void unionTo(int source, int dest) {
			parent[source] = dest;
		}

		@Override
		public boolean judge(int A, int B) {
			return root(A) == root(B);
		}

		@Override
		public Set<Integer> getSet(int id) {
			Set<Integer> set = new HashSet<>();
			IntStream.range(0, size).filter(i -> judge(i, id)).forEach(set::add);
			return set;
		}

		protected int root(int id) {
			if (parent[id] == id) {
				return id;
			}
			parent[id] = root(parent[id]);
			return parent[id];
		}
	}

	/**
	 * 素数のユーティリティ
	 */
	class PrimeNumberUtils {
		boolean[] isPrimeArray;
		List<Integer> primes;

		/**
		 * 素数判定の上限となる値を指定してユーティリティを初期化
		 * @param limit 素数判定の上限(この値以上が素数であるか判定しない)
		 */
		public PrimeNumberUtils(int limit) {
			if (limit > 10000000) {
				System.err.println("上限の値が高すぎるため素数ユーティリティの初期化でTLEする可能性が大変高いです");
			}
			primes = new ArrayList<>();
			isPrimeArray = new boolean[limit];
			if (limit > 2) {
				primes.add(2);
				isPrimeArray[2] = true;
			}

			for (int i = 3; i < limit; i += 2) {
				if (isPrime(i, primes)) {
					primes.add(i);
					isPrimeArray[i] = true;
				}
			}
		}

		public List<Integer> getPrimeNumberList() {
			return primes;
		}

		public boolean isPrime(int n) {
			return isPrimeArray[n];
		}

		private boolean isPrime(int n, List<Integer> primes) {
			for (int prime : primes) {
				if (n % prime == 0) {
					return false;
				}
				if (prime > Math.sqrt(n)) {
					break;
				}
			}
			return true;
		}
	}

	interface BitSet {
		void set(int index, boolean bit);
		boolean get(int index);
		void shiftRight(int num);
		void shiftLeft(int num);
		void or(BitSet bitset);
		void and(BitSet bitset);
	}

	/**
	 * Longの配列によるBitSetの実装
	 * get/setはO(1)
	 * shift/or/andはO(size / 64)
	 */
	class LongBit implements BitSet {
		long[] bitArray;

		public LongBit(int size) {
			bitArray = new long[((size + 63) / 64)];
		}

		@Override
		public void set(int index, boolean bit) {
			int segment = index / 64;
			int inIndex = index % 64;
			if (bit) {
				bitArray[segment] |= 1L << inIndex;
			} else {
				bitArray[segment] &= ~(1L << inIndex);
			}
		}

		@Override
		public boolean get(int index) {
			int segment = index / 64;
			int inIndex = index % 64;
			return (bitArray[segment] & (1L << inIndex)) != 0L;
		}

		@Override
		public void shiftRight(int num) {
			int shiftSeg = num / 64;
			int shiftInI = num % 64;
			for (int segment = 0; segment < bitArray.length; segment++) {
				int sourceSeg = segment + shiftSeg;
				if (sourceSeg < bitArray.length) {
					bitArray[segment] = bitArray[sourceSeg] >>> shiftInI;
					if (shiftInI > 0 && sourceSeg + 1 < bitArray.length) {
						bitArray[segment] |= bitArray[sourceSeg + 1] << (64 - shiftInI);
					}
				} else {
					bitArray[segment] = 0L;
				}
			}
		}

		@Override
		public void shiftLeft(int num) {
			int shiftSeg = num / 64;
			int shiftInI = num % 64;
			for (int segment = bitArray.length - 1; segment >= 0; segment--) {
				int sourceSeg = segment - shiftSeg;
				if (sourceSeg >= 0) {
					bitArray[segment] = bitArray[sourceSeg] << shiftInI;
					if (shiftInI > 0 && sourceSeg > 0) {
						bitArray[segment] |= bitArray[sourceSeg - 1] >>> (64 - shiftInI);
					}
				} else {
					bitArray[segment] = 0L;
				}
			}
		}

		public long getLong(int segment) {
			return bitArray[segment];
		}

		@Override
		public void or(BitSet bitset) {
			if (!(bitset instanceof LongBit)) {
				return;
			}
			for (int segment = 0; segment < bitArray.length; segment++) {
				bitArray[segment] |= ((LongBit)bitset).getLong(segment);
			}
		}

		@Override
		public void and(BitSet bitset) {
			if (!(bitset instanceof LongBit)) {
				return;
			}
			for (int segment = 0; segment < bitArray.length; segment++) {
				bitArray[segment] &= ((LongBit)bitset).getLong(segment);
			}
		}
	}

}


import java.util.Scanner;

public class Main {
	public static void main(String[]args) {
		try(Scanner scan = new Scanner(System.in)){

			int N = scan.nextInt();
			int W = scan.nextInt();
			int[]w = new int[N];
			int[]v = new int[N];
			for(int i = 0;i<N;i++) {
				w[i] = scan.nextInt();
				v[i] = scan.nextInt();
			}

			long[][]dp = new long[N+1][W+1];

			for(int z = 0;z<=W;z++) {
				for(int i = 1;i<=N;i++) {
					if(z-w[i]>=0) {
						dp[i][z] = Math.max(dp[i-1][z-w[i]]+v[i], dp[i-1][z]);
					}else {
						dp[i][z] = dp[i-1][z];
				}
			}
			}

			/*
			for(int i = 0;i<=W;i++) {
				for(int j = 0;j<N;j++) {
					System.out.print(dp[j][i]+" ");
				}
				System.out.println();
			}
			*/

			System.out.println(dp[N][W]);

		}

	}

}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

public class Main {

    public static void main(String[] args) throws Exception {

        ModScanner ms = new ModScanner();
        OutputStream outputStream = System.out;
        PrintWriter out = new PrintWriter(outputStream);
        int n = ms.nextInt();
        int w = ms.nextInt();
        int[] wt = new int[n];
        int[] val = new int[n];
        for (int i = 0; i < n; i++) {
            wt[i] = ms.nextInt();
            val[i] = ms.nextInt();
        }

        out.println(maxProfit(wt, val, w, 0, new HashMap<>()));
        out.close();
    }

    private static long maxProfit(int[] wt, int[] val, int w, int ind, Map<String, Long> cache) {
        if (w < 0) {
            return Long.MIN_VALUE;
        }
        if (w == 0 || ind == wt.length) {
            return 0;
        }
        String key = ind + "|" + w;
        if (!cache.containsKey(key)) {
            long include = maxProfit(wt, val, w - wt[ind], ind + 1, cache) + val[ind];
            long exclude = maxProfit(wt, val, w, ind + 1, cache);
            cache.put(key, Math.max(include, exclude));
        }
        return cache.get(key);
    }

}

class ModScanner {

    BufferedReader br;
    StringTokenizer st;

    public ModScanner() {
        br = new BufferedReader(new InputStreamReader(System.in));
    }

    String nextToken() throws Exception {
        while (st == null || !st.hasMoreElements()) {
            st = new StringTokenizer(br.readLine());

        }
        return st.nextToken();
    }

    String nextString() throws Exception {
        return br.readLine();
    }

    int nextInt() throws Exception, Exception {
        return Integer.parseInt(nextToken());
    }

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

    double nextDouble() throws Exception {
        return Double.parseDouble(nextToken());
    }

}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

public class Main {

    public static void main(String[] args) throws Exception {

        ModScanner ms = new ModScanner();
        OutputStream outputStream = System.out;
        PrintWriter out = new PrintWriter(outputStream);
        int n = ms.nextInt();
        int w = ms.nextInt();
        int[] wt = new int[n];
        int[] val = new int[n];
        for (int i = 0; i < n; i++) {
            wt[i] = ms.nextInt();
            val[i] = ms.nextInt();
        }

        out.println(maxProfit(wt, val, w, 0, new HashMap<>()));
        out.close();
    }

    private static long maxProfit(int[] wt, int[] val, int w, int ind, Map<String, Long> cache) {
        if (w < 0) {
            return Long.MIN_VALUE;
        }
        if (w == 0 || ind == wt.length) {
            return 0;
        }
        String key = ind + "#" + w;
        if (!cache.containsKey(key)) {
            long include = maxProfit(wt, val, w - wt[ind], ind + 1, cache) + val[ind];
            long exclude = maxProfit(wt, val, w, ind + 1, cache);
            cache.put(key, Math.max(include, exclude));
        }
        return cache.get(key);
    }

}

class ModScanner {

    BufferedReader br;
    StringTokenizer st;

    public ModScanner() {
        br = new BufferedReader(new InputStreamReader(System.in));
    }

    String nextToken() throws Exception {
        while (st == null || !st.hasMoreElements()) {
            st = new StringTokenizer(br.readLine());

        }
        return st.nextToken();
    }

    String nextString() throws Exception {
        return br.readLine();
    }

    int nextInt() throws Exception, Exception {
        return Integer.parseInt(nextToken());
    }

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

    double nextDouble() throws Exception {
        return Double.parseDouble(nextToken());
    }

}


#include <bits/stdc++.h>
using namespace std;

#define all(c) c.begin(),c.end()

template <class T>
struct knapsack {
  T c;
  struct item { T p, w; };
  vector<item> is;
  void add_item(T p, T w) {
    is.push_back({p, w});
  }
  T det(T a, T b, T c, T d) {
    return a * d - b * c;
  }
  T z;
  void expbranch(T p, T w, int s, int t) {
    if (w <= c) {
      if (p >= z) z = p;
      for (; t < is.size(); ++t) {
        if (det(p - z - 1, w - c, is[t].p, is[t].w) < 0) return;
        expbranch(p + is[t].p, w + is[t].w, s, t + 1);
      }
    } else {
      for (; s >= 0; --s) {
        if (det(p - z - 1, w - c, is[s].p, is[s].w) < 0) return;
        expbranch(p - is[s].p, w - is[s].w, s - 1, t);
      }
    }
  }
  T solve() {
    sort(all(is), [](const item &a, const item &b) {
      return a.p * b.w > a.w * b.p;
    });
    T p = 0, w = 0;
    z = 0;
    int b = 0;
    for (; b < is.size() && w <= c; ++b) {
      p += is[b].p;
      w += is[b].w;
    }
    expbranch(p, w, b-1, b);
    return z;
  }
};

int main() {
  int s, n;
  scanf("%d %d", &n, &s);
  knapsack<long long> solver;
  solver.c = s;
  for (int i = 0; i < n; ++i) {
    int v, w;
    scanf("%d %d", &w, &v);
    solver.add_item(v, w);
  }
  printf("%lld\n", solver.solve());
}