Bài tập lập trình - Cơ bản
Trang này tổng hợp 100 bài tập lập trình cơ bản, sắp xếp theo chủ đề từ dễ đến khó, mỗi bài có đáp án minh họa bằng nhiều ngôn ngữ lập trình khác nhau. Nếu bạn đã làm quen với các kiến thức cơ bản, hãy thử sức với các bài tập nâng cao hơn ở trang Bài tập lập trình - Nâng cao.
Mỗi bài đều có phần đáp án gợi ý ở dưới, mặc định ẩn đi - bạn nên tự làm trước, sau đó bấm vào “Xem đáp án” để đối chiếu. Đáp án chỉ là một cách giải, không phải cách duy nhất.
(Một số bài được tham khảo, chuyển ngữ và điều chỉnh độ khó từ danh sách 100+ Python challenging programming exercises.)
Bạn có thể tải file .pdf ở đây: 100 bài tập lập trình cơ bản
Nhóm 1: Input/Output và Toán học cơ bản
Phần tiêu đề “Nhóm 1: Input/Output và Toán học cơ bản”Xem thêm lý thuyết: Nhập dữ liệu từ Bàn phím, In kết quả/thông tin với hàm print().
1. Hello World
Viết chương trình in ra dòng chữ Hello, World!.
Xem đáp án
print("Hello, World!")#include <iostream>
int main() { std::cout << "Hello, World!" << std::endl; return 0;}public class Main { public static void main(String[] args) { System.out.println("Hello, World!"); }}fun main() { println("Hello, World!")}void main() { print("Hello, World!");}2. Tổng hai số
Đọc vào 2 số nguyên a, b từ bàn phím (dùng input()), in ra tổng của chúng.
Xem đáp án
while True: try: a = int(input("Nhập a: ")) break except ValueError: print("Vui lòng nhập một số nguyên hợp lệ!")
while True: try: b = int(input("Nhập b: ")) break except ValueError: print("Vui lòng nhập một số nguyên hợp lệ!")
print(a + b)#include <iostream>#include <limits>using namespace std;
int main() { int a, b;
while (true) { cout << "Nhap a: "; if (cin >> a) break; cout << "Vui long nhap mot so nguyen hop le!" << endl; cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); }
while (true) { cout << "Nhap b: "; if (cin >> b) break; cout << "Vui long nhap mot so nguyen hop le!" << endl; cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); }
cout << a + b << endl; return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int a = 0, b = 0;
while (true) { System.out.print("Nhap a: "); try { a = Integer.parseInt(scanner.nextLine().trim()); break; } catch (NumberFormatException e) { System.out.println("Vui long nhap mot so nguyen hop le!"); } }
while (true) { System.out.print("Nhap b: "); try { b = Integer.parseInt(scanner.nextLine().trim()); break; } catch (NumberFormatException e) { System.out.println("Vui long nhap mot so nguyen hop le!"); } }
System.out.println(a + b); }}fun main() { var a: Int? = null while (a == null) { print("Nhap a: ") a = readLine()?.trim()?.toIntOrNull() if (a == null) println("Vui long nhap mot so nguyen hop le!") }
var b: Int? = null while (b == null) { print("Nhap b: ") b = readLine()?.trim()?.toIntOrNull() if (b == null) println("Vui long nhap mot so nguyen hop le!") }
println(a + b)}import 'dart:io';
void main() { int? a; while (a == null) { stdout.write("Nhap a: "); a = int.tryParse(stdin.readLineSync() ?? ''); if (a == null) print("Vui long nhap mot so nguyen hop le!"); }
int? b; while (b == null) { stdout.write("Nhap b: "); b = int.tryParse(stdin.readLineSync() ?? ''); if (b == null) print("Vui long nhap mot so nguyen hop le!"); }
print(a + b);}3. Chu vi và diện tích hình chữ nhật
Đọc vào chiều dài a và chiều rộng b. Tính chu vi (2*(a+b)) và diện tích (a*b).
Xem đáp án
while True: try: a = float(input("Chiều dài: ")) break except ValueError: print("Vui lòng nhập một số hợp lệ!")
while True: try: b = float(input("Chiều rộng: ")) break except ValueError: print("Vui lòng nhập một số hợp lệ!")
print("Chu vi:", 2 * (a + b))print("Diện tích:", a * b)#include <iostream>using namespace std;
int main() { double a, b; cout << "Chieu dai: "; cin >> a; cout << "Chieu rong: "; cin >> b;
cout << "Chu vi: " << 2 * (a + b) << endl; cout << "Dien tich: " << a * b << endl; return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Chieu dai: "); double a = Double.parseDouble(scanner.nextLine().trim()); System.out.print("Chieu rong: "); double b = Double.parseDouble(scanner.nextLine().trim());
System.out.println("Chu vi: " + 2 * (a + b)); System.out.println("Dien tich: " + a * b); }}fun main() { print("Chieu dai: ") val a = readLine()!!.trim().toDouble() print("Chieu rong: ") val b = readLine()!!.trim().toDouble()
println("Chu vi: ${2 * (a + b)}") println("Dien tich: ${a * b}")}import 'dart:io';
void main() { stdout.write("Chieu dai: "); double a = double.parse(stdin.readLineSync()!); stdout.write("Chieu rong: "); double b = double.parse(stdin.readLineSync()!);
print("Chu vi: ${2 * (a + b)}"); print("Dien tich: ${a * b}");}4. Đổi độ C sang độ F
Đọc vào nhiệt độ theo độ C, in ra nhiệt độ tương ứng theo độ F. Công thức: F = C * 9/5 + 32.
Xem đáp án
while True: try: c = float(input("Nhập độ C: ")) break except ValueError: print("Vui lòng nhập một số hợp lệ!")
f = c * 9 / 5 + 32print(f"{c}°C = {f}°F")#include <iostream>using namespace std;
int main() { double c; cout << "Nhap do C: "; cin >> c;
double f = c * 9 / 5 + 32; cout << c << "C = " << f << "F" << endl; return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Nhap do C: "); double c = Double.parseDouble(scanner.nextLine().trim());
double f = c * 9 / 5 + 32; System.out.println(c + "C = " + f + "F"); }}fun main() { print("Nhap do C: ") val c = readLine()!!.trim().toDouble()
val f = c * 9 / 5 + 32 println("${c}C = ${f}F")}import 'dart:io';
void main() { stdout.write("Nhap do C: "); double c = double.parse(stdin.readLineSync()!);
double f = c * 9 / 5 + 32; print("${c}C = ${f}F");}5. Diện tích và chu vi hình tròn
Đọc vào bán kính r, tính chu vi (2×pi×r) và diện tích (pi×r2), làm tròn 2 chữ số thập phân.
Xem đáp án
import math
while True: try: r = float(input("Nhập bán kính: ")) break except ValueError: print("Vui lòng nhập một số hợp lệ!")
print("Chu vi:", round(2 * math.pi * r, 2))print("Diện tích:", round(math.pi * r ** 2, 2))#include <iostream>#include <cmath>#include <iomanip>using namespace std;
int main() { double r; cout << "Nhap ban kinh: "; cin >> r;
cout << fixed << setprecision(2); cout << "Chu vi: " << 2 * M_PI * r << endl; cout << "Dien tich: " << M_PI * r * r << endl; return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Nhap ban kinh: "); double r = Double.parseDouble(scanner.nextLine().trim());
double chuVi = Math.round(2 * Math.PI * r * 100) / 100.0; double dienTich = Math.round(Math.PI * r * r * 100) / 100.0; System.out.println("Chu vi: " + chuVi); System.out.println("Dien tich: " + dienTich); }}import kotlin.math.PIimport kotlin.math.round
fun main() { print("Nhap ban kinh: ") val r = readLine()!!.trim().toDouble()
val chuVi = round(2 * PI * r * 100) / 100 val dienTich = round(PI * r * r * 100) / 100 println("Chu vi: $chuVi") println("Dien tich: $dienTich")}import 'dart:io';import 'dart:math';
void main() { stdout.write("Nhap ban kinh: "); double r = double.parse(stdin.readLineSync()!);
double chuVi = double.parse((2 * pi * r).toStringAsFixed(2)); double dienTich = double.parse((pi * r * r).toStringAsFixed(2)); print("Chu vi: $chuVi"); print("Dien tich: $dienTich");}6. Đổi giây thành giờ:phút:giây
Đọc vào số giây s, in ra theo định dạng Giờ:Phút:Giây.
Ví dụ:
Input: 3665Output: 1:1:5Xem đáp án
while True: try: s = int(input("Nhập số giây: ")) break except ValueError: print("Vui lòng nhập một số nguyên hợp lệ!")
h = s // 3600m = (s % 3600) // 60sec = s % 60print(f"{h}:{m}:{sec}")#include <iostream>using namespace std;
int main() { int s; cout << "Nhap so giay: "; cin >> s;
int h = s / 3600; int m = (s % 3600) / 60; int sec = s % 60; cout << h << ":" << m << ":" << sec << endl; return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Nhap so giay: "); int s = Integer.parseInt(scanner.nextLine().trim());
int h = s / 3600; int m = (s % 3600) / 60; int sec = s % 60; System.out.println(h + ":" + m + ":" + sec); }}fun main() { print("Nhap so giay: ") val s = readLine()!!.trim().toInt()
val h = s / 3600 val m = (s % 3600) / 60 val sec = s % 60 println("$h:$m:$sec")}import 'dart:io';
void main() { stdout.write("Nhap so giay: "); int s = int.parse(stdin.readLineSync()!);
int h = s ~/ 3600; int m = (s % 3600) ~/ 60; int sec = s % 60; print("$h:$m:$sec");}7. Tính lũy thừa
Đọc vào 2 số nguyên a và n, in ra a mũ n (không dùng ** hoặc pow, dùng vòng lặp).
Xem đáp án
while True: try: a = int(input("Nhập a: ")) break except ValueError: print("Vui lòng nhập một số nguyên hợp lệ!")
while True: try: n = int(input("Nhập n: ")) break except ValueError: print("Vui lòng nhập một số nguyên hợp lệ!")
result = 1for _ in range(n): result *= a
print(result)#include <iostream>using namespace std;
int main() { int a, n; cout << "Nhap a: "; cin >> a; cout << "Nhap n: "; cin >> n;
long long result = 1; for (int i = 0; i < n; i++) { result *= a; }
cout << result << endl; return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Nhap a: "); int a = Integer.parseInt(scanner.nextLine().trim()); System.out.print("Nhap n: "); int n = Integer.parseInt(scanner.nextLine().trim());
long result = 1; for (int i = 0; i < n; i++) { result *= a; }
System.out.println(result); }}fun main() { print("Nhap a: ") val a = readLine()!!.trim().toInt() print("Nhap n: ") val n = readLine()!!.trim().toInt()
var result = 1L repeat(n) { result *= a }
println(result)}import 'dart:io';
void main() { stdout.write("Nhap a: "); int a = int.parse(stdin.readLineSync()!); stdout.write("Nhap n: "); int n = int.parse(stdin.readLineSync()!);
int result = 1; for (int i = 0; i < n; i++) { result *= a; }
print(result);}8. Điểm trung bình
Đọc vào 3 điểm số Toán, Lý, Hóa. In ra điểm trung bình, làm tròn 1 chữ số thập phân.
Xem đáp án
while True: try: math_score = float(input("Điểm Toán: ")) break except ValueError: print("Vui lòng nhập một số hợp lệ!")
while True: try: physics_score = float(input("Điểm Lý: ")) break except ValueError: print("Vui lòng nhập một số hợp lệ!")
while True: try: chemistry_score = float(input("Điểm Hóa: ")) break except ValueError: print("Vui lòng nhập một số hợp lệ!")
print(round((math_score + physics_score + chemistry_score) / 3, 1))#include <iostream>#include <iomanip>using namespace std;
int main() { double mathScore, physicsScore, chemistryScore; cout << "Diem Toan: "; cin >> mathScore; cout << "Diem Ly: "; cin >> physicsScore; cout << "Diem Hoa: "; cin >> chemistryScore;
cout << fixed << setprecision(1); cout << (mathScore + physicsScore + chemistryScore) / 3 << endl; return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Diem Toan: "); double mathScore = Double.parseDouble(scanner.nextLine().trim()); System.out.print("Diem Ly: "); double physicsScore = Double.parseDouble(scanner.nextLine().trim()); System.out.print("Diem Hoa: "); double chemistryScore = Double.parseDouble(scanner.nextLine().trim());
double average = Math.round((mathScore + physicsScore + chemistryScore) / 3 * 10) / 10.0; System.out.println(average); }}import kotlin.math.round
fun main() { print("Diem Toan: ") val mathScore = readLine()!!.trim().toDouble() print("Diem Ly: ") val physicsScore = readLine()!!.trim().toDouble() print("Diem Hoa: ") val chemistryScore = readLine()!!.trim().toDouble()
val average = round((mathScore + physicsScore + chemistryScore) / 3 * 10) / 10 println(average)}import 'dart:io';
void main() { stdout.write("Diem Toan: "); double mathScore = double.parse(stdin.readLineSync()!); stdout.write("Diem Ly: "); double physicsScore = double.parse(stdin.readLineSync()!); stdout.write("Diem Hoa: "); double chemistryScore = double.parse(stdin.readLineSync()!);
double average = ((mathScore + physicsScore + chemistryScore) / 3 * 10).round() / 10; print(average);}9. Đảo ngược số có 2 chữ số
Đọc vào một số nguyên dương có 2 chữ số, in ra số đó khi đảo ngược 2 chữ số.
Ví dụ:
Input: 47Output: 74Xem đáp án
while True: try: n = int(input("Nhập số có 2 chữ số: ")) break except ValueError: print("Vui lòng nhập một số nguyên hợp lệ!")
tens = n // 10ones = n % 10print(ones * 10 + tens)#include <iostream>using namespace std;
int main() { int n; cout << "Nhap so co 2 chu so: "; cin >> n;
int tens = n / 10; int ones = n % 10; cout << ones * 10 + tens << endl; return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Nhap so co 2 chu so: "); int n = Integer.parseInt(scanner.nextLine().trim());
int tens = n / 10; int ones = n % 10; System.out.println(ones * 10 + tens); }}fun main() { print("Nhap so co 2 chu so: ") val n = readLine()!!.trim().toInt()
val tens = n / 10 val ones = n % 10 println(ones * 10 + tens)}import 'dart:io';
void main() { stdout.write("Nhap so co 2 chu so: "); int n = int.parse(stdin.readLineSync()!);
int tens = n ~/ 10; int ones = n % 10; print(ones * 10 + tens);}10. Hoán đổi giá trị 2 biến
Cho 2 biến a = 5, b = 10. Hoán đổi giá trị của chúng mà không dùng biến tạm, rồi in ra kết quả.
Xem đáp án
a, b = 5, 10a, b = b, aprint("a =", a, ", b =", b)#include <iostream>using namespace std;
int main() { int a = 5, b = 10; a = a + b; b = a - b; a = a - b;
cout << "a = " << a << ", b = " << b << endl; return 0;}public class Main { public static void main(String[] args) { int a = 5, b = 10; a = a + b; b = a - b; a = a - b;
System.out.println("a = " + a + ", b = " + b); }}fun main() { var a = 5 var b = 10 a += b b = a - b a -= b
println("a = $a, b = $b")}void main() { int a = 5, b = 10; a = a + b; b = a - b; a = a - b;
print("a = $a, b = $b");}Nhóm 2: Cấu trúc rẽ nhánh (if/elif/else)
Phần tiêu đề “Nhóm 2: Cấu trúc rẽ nhánh (if/elif/else)”Xem thêm lý thuyết: Cấu trúc rẽ nhánh (If-Elif-Else).
11. Kiểm tra chẵn lẻ
Đọc vào một số nguyên n, in ra "Chẵn" nếu n chẵn, "Lẻ" nếu n lẻ.
Ví dụ:
Input: 7Output: LẻXem đáp án
while True: try: n = int(input("Nhập n: ")) break except ValueError: print("Vui lòng nhập một số nguyên hợp lệ!")
print("Chẵn" if n % 2 == 0 else "Lẻ")#include <iostream>using namespace std;
int main() { int n; cout << "Nhap n: "; cin >> n;
cout << (n % 2 == 0 ? "Chan" : "Le") << endl; return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Nhap n: "); int n = Integer.parseInt(scanner.nextLine().trim());
System.out.println(n % 2 == 0 ? "Chan" : "Le"); }}fun main() { print("Nhap n: ") val n = readLine()!!.trim().toInt()
println(if (n % 2 == 0) "Chan" else "Le")}import 'dart:io';
void main() { stdout.write("Nhap n: "); int n = int.parse(stdin.readLineSync()!);
print(n % 2 == 0 ? "Chan" : "Le");}12. Số dương, âm hay bằng 0
Đọc vào một số n. In "Dương" nếu n > 0, "Âm" nếu n < 0, "Bằng 0" nếu n == 0.
Ví dụ:
Input: -5Output: ÂmXem đáp án
while True: try: n = float(input("Nhập n: ")) break except ValueError: print("Vui lòng nhập một số hợp lệ!")
if n > 0: print("Dương")elif n < 0: print("Âm")else: print("Bằng 0")#include <iostream>using namespace std;
int main() { double n; cout << "Nhap n: "; cin >> n;
if (n > 0) { cout << "Duong" << endl; } else if (n < 0) { cout << "Am" << endl; } else { cout << "Bang 0" << endl; } return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Nhap n: "); double n = Double.parseDouble(scanner.nextLine().trim());
if (n > 0) { System.out.println("Duong"); } else if (n < 0) { System.out.println("Am"); } else { System.out.println("Bang 0"); } }}fun main() { print("Nhap n: ") val n = readLine()!!.trim().toDouble()
when { n > 0 -> println("Duong") n < 0 -> println("Am") else -> println("Bang 0") }}import 'dart:io';
void main() { stdout.write("Nhap n: "); double n = double.parse(stdin.readLineSync()!);
if (n > 0) { print("Duong"); } else if (n < 0) { print("Am"); } else { print("Bang 0"); }}13. Số lớn nhất trong 3 số
Đọc vào 3 số a, b, c. In ra số lớn nhất (không dùng hàm max).
Ví dụ:
Input: a=7, b=12, c=9Output: 12Xem đáp án
while True: try: a = float(input("a: ")) break except ValueError: print("Vui lòng nhập một số hợp lệ!")
while True: try: b = float(input("b: ")) break except ValueError: print("Vui lòng nhập một số hợp lệ!")
while True: try: c = float(input("c: ")) break except ValueError: print("Vui lòng nhập một số hợp lệ!")
largest = aif b > largest: largest = bif c > largest: largest = c
print(largest)#include <iostream>using namespace std;
int main() { double a, b, c; cout << "a: "; cin >> a; cout << "b: "; cin >> b; cout << "c: "; cin >> c;
double largest = a; if (b > largest) largest = b; if (c > largest) largest = c;
cout << largest << endl; return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("a: "); double a = Double.parseDouble(scanner.nextLine().trim()); System.out.print("b: "); double b = Double.parseDouble(scanner.nextLine().trim()); System.out.print("c: "); double c = Double.parseDouble(scanner.nextLine().trim());
double largest = a; if (b > largest) largest = b; if (c > largest) largest = c;
System.out.println(largest); }}fun main() { print("a: ") val a = readLine()!!.trim().toDouble() print("b: ") val b = readLine()!!.trim().toDouble() print("c: ") val c = readLine()!!.trim().toDouble()
var largest = a if (b > largest) largest = b if (c > largest) largest = c
println(largest)}import 'dart:io';
void main() { stdout.write("a: "); double a = double.parse(stdin.readLineSync()!); stdout.write("b: "); double b = double.parse(stdin.readLineSync()!); stdout.write("c: "); double c = double.parse(stdin.readLineSync()!);
double largest = a; if (b > largest) largest = b; if (c > largest) largest = c;
print(largest);}14. Kiểm tra năm nhuận
Đọc vào năm N. In "Nhuận" nếu N chia hết cho 400, hoặc chia hết cho 4 nhưng không chia hết cho 100.
Ví dụ:
Input: 2024Output: NhuậnXem đáp án
while True: try: n = int(input("Nhập năm: ")) break except ValueError: print("Vui lòng nhập một số nguyên hợp lệ!")
# Năm nhuận: chia hết cho 400, hoặc (chia hết cho 4 và không chia hết cho 100)if n % 400 == 0 or (n % 4 == 0 and n % 100 != 0): print("Nhuận")else: print("Không nhuận")#include <iostream>using namespace std;
int main() { int n; cout << "Nhap nam: "; cin >> n;
if (n % 400 == 0 || (n % 4 == 0 && n % 100 != 0)) { cout << "Nhuan" << endl; } else { cout << "Khong nhuan" << endl; } return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Nhap nam: "); int n = Integer.parseInt(scanner.nextLine().trim());
if (n % 400 == 0 || (n % 4 == 0 && n % 100 != 0)) { System.out.println("Nhuan"); } else { System.out.println("Khong nhuan"); } }}fun main() { print("Nhap nam: ") val n = readLine()!!.trim().toInt()
if (n % 400 == 0 || (n % 4 == 0 && n % 100 != 0)) { println("Nhuan") } else { println("Khong nhuan") }}import 'dart:io';
void main() { stdout.write("Nhap nam: "); int n = int.parse(stdin.readLineSync()!);
if (n % 400 == 0 || (n % 4 == 0 && n % 100 != 0)) { print("Nhuan"); } else { print("Khong nhuan"); }}15. Xếp loại học lực
Đọc điểm trung bình diem (0-10). Xếp loại: >= 8: Giỏi, >= 6.5: Khá, >= 5: Trung bình, còn lại: Yếu.
Ví dụ:
Input: 7.2Output: KháXem đáp án
while True: try: score = float(input("Điểm trung bình: ")) break except ValueError: print("Vui lòng nhập một số hợp lệ!")
if score >= 8: print("Giỏi")elif score >= 6.5: print("Khá")elif score >= 5: print("Trung bình")else: print("Yếu")#include <iostream>using namespace std;
int main() { double score; cout << "Diem trung binh: "; cin >> score;
if (score >= 8) { cout << "Gioi" << endl; } else if (score >= 6.5) { cout << "Kha" << endl; } else if (score >= 5) { cout << "Trung binh" << endl; } else { cout << "Yeu" << endl; } return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Diem trung binh: "); double score = Double.parseDouble(scanner.nextLine().trim());
if (score >= 8) { System.out.println("Gioi"); } else if (score >= 6.5) { System.out.println("Kha"); } else if (score >= 5) { System.out.println("Trung binh"); } else { System.out.println("Yeu"); } }}fun main() { print("Diem trung binh: ") val score = readLine()!!.trim().toDouble()
when { score >= 8 -> println("Gioi") score >= 6.5 -> println("Kha") score >= 5 -> println("Trung binh") else -> println("Yeu") }}import 'dart:io';
void main() { stdout.write("Diem trung binh: "); double score = double.parse(stdin.readLineSync()!);
if (score >= 8) { print("Gioi"); } else if (score >= 6.5) { print("Kha"); } else if (score >= 5) { print("Trung binh"); } else { print("Yeu"); }}16. Kiểm tra tam giác
Đọc vào 3 số dương a, b, c. Kiểm tra 3 số đó có tạo thành tam giác hay không (tổng 2 cạnh bất kỳ phải lớn hơn cạnh còn lại).
Ví dụ:
Input: a=3, b=4, c=5Output: Là tam giácXem đáp án
while True: try: a = float(input("a: ")) break except ValueError: print("Vui lòng nhập một số hợp lệ!")
while True: try: b = float(input("b: ")) break except ValueError: print("Vui lòng nhập một số hợp lệ!")
while True: try: c = float(input("c: ")) break except ValueError: print("Vui lòng nhập một số hợp lệ!")
if a + b > c and a + c > b and b + c > a: print("Là tam giác")else: print("Không phải là tam giác")#include <iostream>using namespace std;
int main() { double a, b, c; cout << "a: "; cin >> a; cout << "b: "; cin >> b; cout << "c: "; cin >> c;
if (a + b > c && a + c > b && b + c > a) { cout << "La tam giac" << endl; } else { cout << "Khong phai la tam giac" << endl; } return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("a: "); double a = Double.parseDouble(scanner.nextLine().trim()); System.out.print("b: "); double b = Double.parseDouble(scanner.nextLine().trim()); System.out.print("c: "); double c = Double.parseDouble(scanner.nextLine().trim());
if (a + b > c && a + c > b && b + c > a) { System.out.println("La tam giac"); } else { System.out.println("Khong phai la tam giac"); } }}fun main() { print("a: ") val a = readLine()!!.trim().toDouble() print("b: ") val b = readLine()!!.trim().toDouble() print("c: ") val c = readLine()!!.trim().toDouble()
if (a + b > c && a + c > b && b + c > a) { println("La tam giac") } else { println("Khong phai la tam giac") }}import 'dart:io';
void main() { stdout.write("a: "); double a = double.parse(stdin.readLineSync()!); stdout.write("b: "); double b = double.parse(stdin.readLineSync()!); stdout.write("c: "); double c = double.parse(stdin.readLineSync()!);
if (a + b > c && a + c > b && b + c > a) { print("La tam giac"); } else { print("Khong phai la tam giac"); }}17. Giải phương trình bậc nhất
Đọc vào 2 hệ số a, b của phương trình ax + b = 0. In ra nghiệm, hoặc thông báo phù hợp nếu vô nghiệm/vô số nghiệm.
Ví dụ:
Input: a=2, b=-4Output: x = 2.0Xem đáp án
while True: try: a = float(input("a: ")) break except ValueError: print("Vui lòng nhập một số hợp lệ!")
while True: try: b = float(input("b: ")) break except ValueError: print("Vui lòng nhập một số hợp lệ!")
if a == 0: if b == 0: print("Phương trình vô số nghiệm") else: print("Phương trình vô nghiệm")else: print("x =", -b / a)#include <iostream>using namespace std;
int main() { double a, b; cout << "a: "; cin >> a; cout << "b: "; cin >> b;
if (a == 0) { if (b == 0) { cout << "Phuong trinh vo so nghiem" << endl; } else { cout << "Phuong trinh vo nghiem" << endl; } } else { cout << "x = " << -b / a << endl; } return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("a: "); double a = Double.parseDouble(scanner.nextLine().trim()); System.out.print("b: "); double b = Double.parseDouble(scanner.nextLine().trim());
if (a == 0) { if (b == 0) { System.out.println("Phuong trinh vo so nghiem"); } else { System.out.println("Phuong trinh vo nghiem"); } } else { System.out.println("x = " + (-b / a)); } }}fun main() { print("a: ") val a = readLine()!!.trim().toDouble() print("b: ") val b = readLine()!!.trim().toDouble()
if (a == 0.0) { if (b == 0.0) { println("Phuong trinh vo so nghiem") } else { println("Phuong trinh vo nghiem") } } else { println("x = ${-b / a}") }}import 'dart:io';
void main() { stdout.write("a: "); double a = double.parse(stdin.readLineSync()!); stdout.write("b: "); double b = double.parse(stdin.readLineSync()!);
if (a == 0) { if (b == 0) { print("Phuong trinh vo so nghiem"); } else { print("Phuong trinh vo nghiem"); } } else { print("x = ${-b / a}"); }}18. Tính tiền điện
Đọc số điện tiêu thụ kwh. Giá: 50 số đầu 1,678đ/số; 50 số tiếp theo 1,734đ/số; từ số 101 trở lên 2,014đ/số. In ra tổng tiền phải trả.
Ví dụ:
Input: 120Output: 210880 đồngXem đáp án
while True: try: kwh = int(input("Số điện tiêu thụ: ")) break except ValueError: print("Vui lòng nhập một số nguyên hợp lệ!")
if kwh <= 50: cost = kwh * 1678elif kwh <= 100: cost = 50 * 1678 + (kwh - 50) * 1734else: cost = 50 * 1678 + 50 * 1734 + (kwh - 100) * 2014
print("Tiền điện:", cost, "đồng")#include <iostream>using namespace std;
int main() { int kwh; cout << "So dien tieu thu: "; cin >> kwh;
long cost; if (kwh <= 50) { cost = kwh * 1678; } else if (kwh <= 100) { cost = 50 * 1678 + (kwh - 50) * 1734; } else { cost = 50 * 1678 + 50 * 1734 + (kwh - 100) * 2014; }
cout << "Tien dien: " << cost << " dong" << endl; return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("So dien tieu thu: "); int kwh = Integer.parseInt(scanner.nextLine().trim());
long cost; if (kwh <= 50) { cost = kwh * 1678L; } else if (kwh <= 100) { cost = 50 * 1678L + (kwh - 50) * 1734L; } else { cost = 50 * 1678L + 50 * 1734L + (kwh - 100) * 2014L; }
System.out.println("Tien dien: " + cost + " dong"); }}fun main() { print("So dien tieu thu: ") val kwh = readLine()!!.trim().toInt()
val cost = when { kwh <= 50 -> kwh * 1678L kwh <= 100 -> 50 * 1678L + (kwh - 50) * 1734L else -> 50 * 1678L + 50 * 1734L + (kwh - 100) * 2014L }
println("Tien dien: $cost dong")}import 'dart:io';
void main() { stdout.write("So dien tieu thu: "); int kwh = int.parse(stdin.readLineSync()!);
int cost; if (kwh <= 50) { cost = kwh * 1678; } else if (kwh <= 100) { cost = 50 * 1678 + (kwh - 50) * 1734; } else { cost = 50 * 1678 + 50 * 1734 + (kwh - 100) * 2014; }
print("Tien dien: $cost dong");}19. Kiểm tra ký tự
Đọc vào 1 ký tự. In ra đó là chữ cái in hoa, chữ cái in thường, chữ số, hay ký tự đặc biệt.
Ví dụ:
Input: AOutput: Chữ in hoaXem đáp án
while True: c = input("Nhập 1 ký tự: ") if len(c) == 1: break print("Vui lòng nhập đúng 1 ký tự!")
if c.isupper(): print("Chữ in hoa")elif c.islower(): print("Chữ in thường")elif c.isdigit(): print("Chữ số")else: print("Ký tự đặc biệt")#include <iostream>#include <cctype>using namespace std;
int main() { char c; cout << "Nhap 1 ky tu: "; cin >> c;
if (isupper(c)) { cout << "Chu in hoa" << endl; } else if (islower(c)) { cout << "Chu in thuong" << endl; } else if (isdigit(c)) { cout << "Chu so" << endl; } else { cout << "Ky tu dac biet" << endl; } return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Nhap 1 ky tu: "); char c = scanner.nextLine().trim().charAt(0);
if (Character.isUpperCase(c)) { System.out.println("Chu in hoa"); } else if (Character.isLowerCase(c)) { System.out.println("Chu in thuong"); } else if (Character.isDigit(c)) { System.out.println("Chu so"); } else { System.out.println("Ky tu dac biet"); } }}fun main() { print("Nhap 1 ky tu: ") val c = readLine()!!.trim()[0]
when { c.isUpperCase() -> println("Chu in hoa") c.isLowerCase() -> println("Chu in thuong") c.isDigit() -> println("Chu so") else -> println("Ky tu dac biet") }}import 'dart:io';
void main() { stdout.write("Nhap 1 ky tu: "); String c = stdin.readLineSync()!.trim(); int code = c.codeUnitAt(0);
if (code >= 65 && code <= 90) { print("Chu in hoa"); } else if (code >= 97 && code <= 122) { print("Chu in thuong"); } else if (code >= 48 && code <= 57) { print("Chu so"); } else { print("Ky tu dac biet"); }}20. Máy tính đơn giản
Đọc vào 2 số a, b và 1 phép toán (+, -, *, /). In ra kết quả tương ứng.
Ví dụ:
Input: a=10, op=+, b=5Output: 15.0Xem đáp án
while True: try: a = float(input("a: ")) break except ValueError: print("Vui lòng nhập một số hợp lệ!")
while True: op = input("Phép toán (+ - * /): ") if op in ("+", "-", "*", "/"): break print("Vui lòng nhập đúng 1 trong các phép toán: + - * /")
while True: try: b = float(input("b: ")) break except ValueError: print("Vui lòng nhập một số hợp lệ!")
if op == "+": print(a + b)elif op == "-": print(a - b)elif op == "*": print(a * b)else: print(a / b if b != 0 else "Không thể chia cho 0")#include <iostream>using namespace std;
int main() { double a, b; char op; cout << "a: "; cin >> a; cout << "Phep toan (+ - * /): "; cin >> op; cout << "b: "; cin >> b;
if (op == '+') { cout << a + b << endl; } else if (op == '-') { cout << a - b << endl; } else if (op == '*') { cout << a * b << endl; } else if (b != 0) { cout << a / b << endl; } else { cout << "Khong the chia cho 0" << endl; } return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("a: "); double a = Double.parseDouble(scanner.nextLine().trim()); System.out.print("Phep toan (+ - * /): "); String op = scanner.nextLine().trim(); System.out.print("b: "); double b = Double.parseDouble(scanner.nextLine().trim());
switch (op) { case "+": System.out.println(a + b); break; case "-": System.out.println(a - b); break; case "*": System.out.println(a * b); break; default: System.out.println(b != 0 ? a / b : "Khong the chia cho 0"); } }}fun main() { print("a: ") val a = readLine()!!.trim().toDouble() print("Phep toan (+ - * /): ") val op = readLine()!!.trim() print("b: ") val b = readLine()!!.trim().toDouble()
when (op) { "+" -> println(a + b) "-" -> println(a - b) "*" -> println(a * b) else -> println(if (b != 0.0) a / b else "Khong the chia cho 0") }}import 'dart:io';
void main() { stdout.write("a: "); double a = double.parse(stdin.readLineSync()!); stdout.write("Phep toan (+ - * /): "); String op = stdin.readLineSync()!.trim(); stdout.write("b: "); double b = double.parse(stdin.readLineSync()!);
switch (op) { case "+": print(a + b); break; case "-": print(a - b); break; case "*": print(a * b); break; default: print(b != 0 ? a / b : "Khong the chia cho 0"); }}Nhóm 3: Vòng lặp (for, while)
Phần tiêu đề “Nhóm 3: Vòng lặp (for, while)”Xem thêm lý thuyết: Vòng lặp for với hàm range(), Vòng lặp while, Break, Continue và Pass.
21. In các số từ 1 đến n
Đọc vào số nguyên n, in ra các số từ 1 đến n, mỗi số trên 1 dòng.
Xem đáp án
while True: try: n = int(input("Nhập n: ")) break except ValueError: print("Vui lòng nhập một số nguyên hợp lệ!")
for i in range(1, n + 1): print(i)#include <iostream>using namespace std;
int main() { int n; cout << "Nhap n: "; cin >> n;
for (int i = 1; i <= n; i++) { cout << i << endl; } return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Nhap n: "); int n = Integer.parseInt(scanner.nextLine().trim());
for (int i = 1; i <= n; i++) { System.out.println(i); } }}fun main() { print("Nhap n: ") val n = readLine()!!.trim().toInt()
for (i in 1..n) { println(i) }}import 'dart:io';
void main() { stdout.write("Nhap n: "); int n = int.parse(stdin.readLineSync()!);
for (int i = 1; i <= n; i++) { print(i); }}22. Tính tổng 1 + 2 + … + n
Đọc vào n, tính tổng các số từ 1 đến n.
Xem đáp án
while True: try: n = int(input("Nhập n: ")) break except ValueError: print("Vui lòng nhập một số nguyên hợp lệ!")
total = 0for i in range(1, n + 1): total += i
print(total)#include <iostream>using namespace std;
int main() { int n; cout << "Nhap n: "; cin >> n;
long long total = 0; for (int i = 1; i <= n; i++) { total += i; }
cout << total << endl; return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Nhap n: "); int n = Integer.parseInt(scanner.nextLine().trim());
long total = 0; for (int i = 1; i <= n; i++) { total += i; }
System.out.println(total); }}fun main() { print("Nhap n: ") val n = readLine()!!.trim().toInt()
var total = 0L for (i in 1..n) { total += i }
println(total)}import 'dart:io';
void main() { stdout.write("Nhap n: "); int n = int.parse(stdin.readLineSync()!);
int total = 0; for (int i = 1; i <= n; i++) { total += i; }
print(total);}23. Tính giai thừa
Đọc vào n, tính n! (giai thừa của n).
Xem đáp án
while True: try: n = int(input("Nhập n: ")) break except ValueError: print("Vui lòng nhập một số nguyên hợp lệ!")
result = 1for i in range(1, n + 1): result *= i
print(result)#include <iostream>using namespace std;
int main() { int n; cout << "Nhap n: "; cin >> n;
long long result = 1; for (int i = 1; i <= n; i++) { result *= i; }
cout << result << endl; return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Nhap n: "); int n = Integer.parseInt(scanner.nextLine().trim());
long result = 1; for (int i = 1; i <= n; i++) { result *= i; }
System.out.println(result); }}fun main() { print("Nhap n: ") val n = readLine()!!.trim().toInt()
var result = 1L for (i in 1..n) { result *= i }
println(result)}import 'dart:io';
void main() { stdout.write("Nhap n: "); int n = int.parse(stdin.readLineSync()!);
int result = 1; for (int i = 1; i <= n; i++) { result *= i; }
print(result);}24. Bảng cửu chương
Đọc vào số n, in ra bảng cửu chương của n (từ n x 1 đến n x 10).
Xem đáp án
while True: try: n = int(input("Nhập n: ")) break except ValueError: print("Vui lòng nhập một số nguyên hợp lệ!")
for i in range(1, 11): print(f"{n} x {i} = {n * i}")#include <iostream>using namespace std;
int main() { int n; cout << "Nhap n: "; cin >> n;
for (int i = 1; i <= 10; i++) { cout << n << " x " << i << " = " << n * i << endl; } return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Nhap n: "); int n = Integer.parseInt(scanner.nextLine().trim());
for (int i = 1; i <= 10; i++) { System.out.println(n + " x " + i + " = " + (n * i)); } }}fun main() { print("Nhap n: ") val n = readLine()!!.trim().toInt()
for (i in 1..10) { println("$n x $i = ${n * i}") }}import 'dart:io';
void main() { stdout.write("Nhap n: "); int n = int.parse(stdin.readLineSync()!);
for (int i = 1; i <= 10; i++) { print("$n x $i = ${n * i}"); }}25. Đếm số chữ số của một số
Đọc vào một số nguyên dương, đếm xem nó có bao nhiêu chữ số.
Ví dụ:
Input: 12345Output: 5Xem đáp án
while True: try: n = int(input("Nhập số: ")) break except ValueError: print("Vui lòng nhập một số nguyên hợp lệ!")
count = 0while n > 0: n = n // 10 count += 1
print(count)#include <iostream>using namespace std;
int main() { int n; cout << "Nhap so: "; cin >> n;
int count = 0; while (n > 0) { n = n / 10; count++; }
cout << count << endl; return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Nhap so: "); int n = Integer.parseInt(scanner.nextLine().trim());
int count = 0; while (n > 0) { n = n / 10; count++; }
System.out.println(count); }}fun main() { print("Nhap so: ") var n = readLine()!!.trim().toInt()
var count = 0 while (n > 0) { n /= 10 count++ }
println(count)}import 'dart:io';
void main() { stdout.write("Nhap so: "); int n = int.parse(stdin.readLineSync()!);
int count = 0; while (n > 0) { n = n ~/ 10; count++; }
print(count);}26. Tính tổng các chữ số
Đọc vào một số nguyên dương, tính tổng các chữ số của nó.
Ví dụ:
Input: 12345Output: 15Xem đáp án
while True: try: n = int(input("Nhập số: ")) break except ValueError: print("Vui lòng nhập một số nguyên hợp lệ!")
total = 0while n > 0: total += n % 10 n = n // 10
print(total)#include <iostream>using namespace std;
int main() { int n; cout << "Nhap so: "; cin >> n;
int total = 0; while (n > 0) { total += n % 10; n = n / 10; }
cout << total << endl; return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Nhap so: "); int n = Integer.parseInt(scanner.nextLine().trim());
int total = 0; while (n > 0) { total += n % 10; n = n / 10; }
System.out.println(total); }}fun main() { print("Nhap so: ") var n = readLine()!!.trim().toInt()
var total = 0 while (n > 0) { total += n % 10 n /= 10 }
println(total)}import 'dart:io';
void main() { stdout.write("Nhap so: "); int n = int.parse(stdin.readLineSync()!);
int total = 0; while (n > 0) { total += n % 10; n = n ~/ 10; }
print(total);}27. Kiểm tra số nguyên tố
Đọc vào số nguyên dương n, kiểm tra n có phải số nguyên tố hay không.
Ví dụ:
Input: 17Output: Là số nguyên tốXem đáp án
while True: try: n = int(input("Nhập n: ")) break except ValueError: print("Vui lòng nhập một số nguyên hợp lệ!")
if n < 2: print("Không phải số nguyên tố")else: is_prime = True for i in range(2, int(n ** 0.5) + 1): if n % i == 0: is_prime = False break print("Là số nguyên tố" if is_prime else "Không phải số nguyên tố")#include <iostream>#include <cmath>using namespace std;
int main() { int n; cout << "Nhap n: "; cin >> n;
bool isPrime = n >= 2; for (int i = 2; i <= (int)sqrt(n) && isPrime; i++) { if (n % i == 0) isPrime = false; }
cout << (isPrime ? "La so nguyen to" : "Khong phai so nguyen to") << endl; return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Nhap n: "); int n = Integer.parseInt(scanner.nextLine().trim());
boolean isPrime = n >= 2; for (int i = 2; i <= Math.sqrt(n) && isPrime; i++) { if (n % i == 0) isPrime = false; }
System.out.println(isPrime ? "La so nguyen to" : "Khong phai so nguyen to"); }}import kotlin.math.sqrt
fun main() { print("Nhap n: ") val n = readLine()!!.trim().toInt()
var isPrime = n >= 2 var i = 2 while (i <= sqrt(n.toDouble()) && isPrime) { if (n % i == 0) isPrime = false i++ }
println(if (isPrime) "La so nguyen to" else "Khong phai so nguyen to")}import 'dart:io';import 'dart:math';
void main() { stdout.write("Nhap n: "); int n = int.parse(stdin.readLineSync()!);
bool isPrime = n >= 2; for (int i = 2; i <= sqrt(n) && isPrime; i++) { if (n % i == 0) isPrime = false; }
print(isPrime ? "La so nguyen to" : "Khong phai so nguyen to");}28. In các số nguyên tố nhỏ hơn n
Đọc vào n, in ra tất cả các số nguyên tố nhỏ hơn n.
Ví dụ:
Input: 20Output: 2 3 5 7 11 13 17 19Xem đáp án
while True: try: n = int(input("Nhập n: ")) break except ValueError: print("Vui lòng nhập một số nguyên hợp lệ!")
for num in range(2, n): is_prime = True for i in range(2, int(num ** 0.5) + 1): if num % i == 0: is_prime = False break if is_prime: print(num, end=" ")#include <iostream>#include <cmath>using namespace std;
int main() { int n; cout << "Nhap n: "; cin >> n;
for (int num = 2; num < n; num++) { bool isPrime = true; for (int i = 2; i <= (int)sqrt(num); i++) { if (num % i == 0) { isPrime = false; break; } } if (isPrime) cout << num << " "; } return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Nhap n: "); int n = Integer.parseInt(scanner.nextLine().trim());
for (int num = 2; num < n; num++) { boolean isPrime = true; for (int i = 2; i <= Math.sqrt(num); i++) { if (num % i == 0) { isPrime = false; break; } } if (isPrime) System.out.print(num + " "); } }}import kotlin.math.sqrt
fun main() { print("Nhap n: ") val n = readLine()!!.trim().toInt()
for (num in 2 until n) { var isPrime = true for (i in 2..sqrt(num.toDouble()).toInt()) { if (num % i == 0) { isPrime = false break } } if (isPrime) print("$num ") }}import 'dart:io';import 'dart:math';
void main() { stdout.write("Nhap n: "); int n = int.parse(stdin.readLineSync()!);
for (int num = 2; num < n; num++) { bool isPrime = true; for (int i = 2; i <= sqrt(num); i++) { if (num % i == 0) { isPrime = false; break; } } if (isPrime) stdout.write("$num "); }}29. Ước chung lớn nhất (ƯCLN)
Đọc vào 2 số nguyên dương a, b, tính ƯCLN của chúng (dùng thuật toán Euclid).
Ví dụ:
Input: a=48, b=18Output: ƯCLN: 6Xem đáp án
while True: try: a = int(input("a: ")) break except ValueError: print("Vui lòng nhập một số nguyên hợp lệ!")
while True: try: b = int(input("b: ")) break except ValueError: print("Vui lòng nhập một số nguyên hợp lệ!")
while b != 0: a, b = b, a % b
print("ƯCLN:", a)#include <iostream>using namespace std;
int main() { int a, b; cout << "a: "; cin >> a; cout << "b: "; cin >> b;
while (b != 0) { int temp = b; b = a % b; a = temp; }
cout << "UCLN: " << a << endl; return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("a: "); int a = Integer.parseInt(scanner.nextLine().trim()); System.out.print("b: "); int b = Integer.parseInt(scanner.nextLine().trim());
while (b != 0) { int temp = b; b = a % b; a = temp; }
System.out.println("UCLN: " + a); }}fun main() { print("a: ") var a = readLine()!!.trim().toInt() print("b: ") var b = readLine()!!.trim().toInt()
while (b != 0) { val temp = b b = a % b a = temp }
println("UCLN: $a")}import 'dart:io';
void main() { stdout.write("a: "); int a = int.parse(stdin.readLineSync()!); stdout.write("b: "); int b = int.parse(stdin.readLineSync()!);
while (b != 0) { int temp = b; b = a % b; a = temp; }
print("UCLN: $a");}30. Bội chung nhỏ nhất (BCNN)
Đọc vào 2 số nguyên dương a, b, tính BCNN của chúng (dựa vào ƯCLN: BCNN = a*b / ƯCLN).
Ví dụ:
Input: a=4, b=6Output: BCNN: 12Xem đáp án
while True: try: a = int(input("a: ")) break except ValueError: print("Vui lòng nhập một số nguyên hợp lệ!")
while True: try: b = int(input("b: ")) break except ValueError: print("Vui lòng nhập một số nguyên hợp lệ!")
x, y = a, bwhile y != 0: x, y = y, x % ygcd_value = x
print("BCNN:", a * b // gcd_value)#include <iostream>using namespace std;
int main() { int a, b; cout << "a: "; cin >> a; cout << "b: "; cin >> b;
int x = a, y = b; while (y != 0) { int temp = y; y = x % y; x = temp; }
cout << "BCNN: " << a * b / x << endl; return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("a: "); int a = Integer.parseInt(scanner.nextLine().trim()); System.out.print("b: "); int b = Integer.parseInt(scanner.nextLine().trim());
int x = a, y = b; while (y != 0) { int temp = y; y = x % y; x = temp; }
System.out.println("BCNN: " + a * b / x); }}fun main() { print("a: ") val a = readLine()!!.trim().toInt() print("b: ") val b = readLine()!!.trim().toInt()
var x = a var y = b while (y != 0) { val temp = y y = x % y x = temp }
println("BCNN: ${a * b / x}")}import 'dart:io';
void main() { stdout.write("a: "); int a = int.parse(stdin.readLineSync()!); stdout.write("b: "); int b = int.parse(stdin.readLineSync()!);
int x = a, y = b; while (y != 0) { int temp = y; y = x % y; x = temp; }
print("BCNN: ${a * b ~/ x}");}31. Dãy Fibonacci
Đọc vào n, in ra n số đầu tiên của dãy Fibonacci (0, 1, 1, 2, 3, 5, …).
Ví dụ:
Input: 7Output: 0 1 1 2 3 5 8Xem đáp án
while True: try: n = int(input("Nhập n: ")) break except ValueError: print("Vui lòng nhập một số nguyên hợp lệ!")
a, b = 0, 1for _ in range(n): print(a, end=" ") a, b = b, a + b#include <iostream>using namespace std;
int main() { int n; cout << "Nhap n: "; cin >> n;
long long a = 0, b = 1; for (int i = 0; i < n; i++) { cout << a << " "; long long temp = a + b; a = b; b = temp; } return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Nhap n: "); int n = Integer.parseInt(scanner.nextLine().trim());
long a = 0, b = 1; for (int i = 0; i < n; i++) { System.out.print(a + " "); long temp = a + b; a = b; b = temp; } }}fun main() { print("Nhap n: ") val n = readLine()!!.trim().toInt()
var a = 0L var b = 1L repeat(n) { print("$a ") val temp = a + b a = b b = temp }}import 'dart:io';
void main() { stdout.write("Nhap n: "); int n = int.parse(stdin.readLineSync()!);
int a = 0, b = 1; for (int i = 0; i < n; i++) { stdout.write("$a "); int temp = a + b; a = b; b = temp; }}32. Số hoàn hảo
Một số được gọi là số hoàn hảo nếu nó bằng tổng các ước số dương nhỏ hơn nó (ví dụ: 6 = 1 + 2 + 3). In ra tất cả số hoàn hảo trong khoảng từ 1 đến n.
Ví dụ:
Input: 30Output: 6 28Xem đáp án
while True: try: n = int(input("Nhập n: ")) break except ValueError: print("Vui lòng nhập một số nguyên hợp lệ!")
for num in range(1, n + 1): divisor_sum = sum(i for i in range(1, num) if num % i == 0) if divisor_sum == num: print(num, end=" ")#include <iostream>using namespace std;
int main() { int n; cout << "Nhap n: "; cin >> n;
for (int num = 1; num <= n; num++) { int divisorSum = 0; for (int i = 1; i < num; i++) { if (num % i == 0) divisorSum += i; } if (divisorSum == num) cout << num << " "; } return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Nhap n: "); int n = Integer.parseInt(scanner.nextLine().trim());
for (int num = 1; num <= n; num++) { int divisorSum = 0; for (int i = 1; i < num; i++) { if (num % i == 0) divisorSum += i; } if (divisorSum == num) System.out.print(num + " "); } }}fun main() { print("Nhap n: ") val n = readLine()!!.trim().toInt()
for (num in 1..n) { var divisorSum = 0 for (i in 1 until num) { if (num % i == 0) divisorSum += i } if (divisorSum == num) print("$num ") }}import 'dart:io';
void main() { stdout.write("Nhap n: "); int n = int.parse(stdin.readLineSync()!);
for (int num = 1; num <= n; num++) { int divisorSum = 0; for (int i = 1; i < num; i++) { if (num % i == 0) divisorSum += i; } if (divisorSum == num) stdout.write("$num "); }}33. In hình tam giác dấu sao
Đọc vào n, in ra hình tam giác vuông bằng dấu * có n dòng.
Ví dụ với n = 4:
**********Xem đáp án
while True: try: n = int(input("Nhập n: ")) break except ValueError: print("Vui lòng nhập một số nguyên hợp lệ!")
for i in range(1, n + 1): print("*" * i)#include <iostream>#include <string>using namespace std;
int main() { int n; cout << "Nhap n: "; cin >> n;
for (int i = 1; i <= n; i++) { cout << string(i, '*') << endl; } return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Nhap n: "); int n = Integer.parseInt(scanner.nextLine().trim());
for (int i = 1; i <= n; i++) { System.out.println("*".repeat(i)); } }}fun main() { print("Nhap n: ") val n = readLine()!!.trim().toInt()
for (i in 1..n) { println("*".repeat(i)) }}import 'dart:io';
void main() { stdout.write("Nhap n: "); int n = int.parse(stdin.readLineSync()!);
for (int i = 1; i <= n; i++) { print("*" * i); }}34. In hình tam giác cân dấu sao
Đọc vào n, in ra hình tam giác cân bằng dấu * có n dòng, căn giữa.
Ví dụ với n = 3:
* ********Xem đáp án
while True: try: n = int(input("Nhập n: ")) break except ValueError: print("Vui lòng nhập một số nguyên hợp lệ!")
for i in range(1, n + 1): spaces = " " * (n - i) stars = "*" * (2 * i - 1) print(spaces + stars)#include <iostream>#include <string>using namespace std;
int main() { int n; cout << "Nhap n: "; cin >> n;
for (int i = 1; i <= n; i++) { cout << string(n - i, ' ') << string(2 * i - 1, '*') << endl; } return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Nhap n: "); int n = Integer.parseInt(scanner.nextLine().trim());
for (int i = 1; i <= n; i++) { System.out.println(" ".repeat(n - i) + "*".repeat(2 * i - 1)); } }}fun main() { print("Nhap n: ") val n = readLine()!!.trim().toInt()
for (i in 1..n) { println(" ".repeat(n - i) + "*".repeat(2 * i - 1)) }}import 'dart:io';
void main() { stdout.write("Nhap n: "); int n = int.parse(stdin.readLineSync()!);
for (int i = 1; i <= n; i++) { print(" " * (n - i) + "*" * (2 * i - 1)); }}35. Đếm số lần xuất hiện
Đọc vào 1 số n, dùng vòng lặp while để đếm xem cần chia n cho 2 bao nhiêu lần thì về 1 (làm tròn xuống).
Xem đáp án
while True: try: n = int(input("Nhập n: ")) break except ValueError: print("Vui lòng nhập một số nguyên hợp lệ!")
count = 0while n > 1: n = n // 2 count += 1
print(count)#include <iostream>using namespace std;
int main() { int n; cout << "Nhap n: "; cin >> n;
int count = 0; while (n > 1) { n = n / 2; count++; }
cout << count << endl; return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Nhap n: "); int n = Integer.parseInt(scanner.nextLine().trim());
int count = 0; while (n > 1) { n = n / 2; count++; }
System.out.println(count); }}fun main() { print("Nhap n: ") var n = readLine()!!.trim().toInt()
var count = 0 while (n > 1) { n /= 2 count++ }
println(count)}import 'dart:io';
void main() { stdout.write("Nhap n: "); int n = int.parse(stdin.readLineSync()!);
int count = 0; while (n > 1) { n = n ~/ 2; count++; }
print(count);}36. Đoán số (dùng while)
Cho trước một số bí mật secret = 42. Dùng vòng lặp while để yêu cầu người dùng nhập số cho đến khi đoán đúng, in "Đoán đúng rồi!" khi thành công.
Xem đáp án
secret = 42guess = None
while guess != secret: try: guess = int(input("Đoán số: ")) except ValueError: print("Vui lòng nhập một số nguyên hợp lệ!") continue
if guess < secret: print("Thấp hơn") elif guess > secret: print("Cao hơn")
print("Đoán đúng rồi!")#include <iostream>using namespace std;
int main() { int secret = 42; int guess = -1;
while (guess != secret) { cout << "Doan so: "; cin >> guess;
if (guess < secret) { cout << "Thap hon" << endl; } else if (guess > secret) { cout << "Cao hon" << endl; } }
cout << "Doan dung roi!" << endl; return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int secret = 42; int guess = -1;
while (guess != secret) { System.out.print("Doan so: "); guess = Integer.parseInt(scanner.nextLine().trim());
if (guess < secret) { System.out.println("Thap hon"); } else if (guess > secret) { System.out.println("Cao hon"); } }
System.out.println("Doan dung roi!"); }}fun main() { val secret = 42 var guess = -1
while (guess != secret) { print("Doan so: ") guess = readLine()!!.trim().toInt()
if (guess < secret) { println("Thap hon") } else if (guess > secret) { println("Cao hon") } }
println("Doan dung roi!")}import 'dart:io';
void main() { int secret = 42; int guess = -1;
while (guess != secret) { stdout.write("Doan so: "); guess = int.parse(stdin.readLineSync()!);
if (guess < secret) { print("Thap hon"); } else if (guess > secret) { print("Cao hon"); } }
print("Doan dung roi!");}37. Số Armstrong
Một số có 3 chữ số là số Armstrong nếu tổng lập phương các chữ số của nó bằng chính nó (ví dụ: 153 = 13 + 53 + 33). Kiểm tra một số nhập vào có phải số Armstrong không.
Ví dụ:
Input: 153Output: Là số ArmstrongXem đáp án
while True: try: n = int(input("Nhập số có 3 chữ số: ")) break except ValueError: print("Vui lòng nhập một số nguyên hợp lệ!")
hundreds = n // 100tens = (n // 10) % 10ones = n % 10
if hundreds ** 3 + tens ** 3 + ones ** 3 == n: print("Là số Armstrong")else: print("Không phải số Armstrong")#include <iostream>using namespace std;
int main() { int n; cout << "Nhap so co 3 chu so: "; cin >> n;
int hundreds = n / 100; int tens = (n / 10) % 10; int ones = n % 10;
if (hundreds * hundreds * hundreds + tens * tens * tens + ones * ones * ones == n) { cout << "La so Armstrong" << endl; } else { cout << "Khong phai so Armstrong" << endl; } return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Nhap so co 3 chu so: "); int n = Integer.parseInt(scanner.nextLine().trim());
int hundreds = n / 100; int tens = (n / 10) % 10; int ones = n % 10;
if (Math.pow(hundreds, 3) + Math.pow(tens, 3) + Math.pow(ones, 3) == n) { System.out.println("La so Armstrong"); } else { System.out.println("Khong phai so Armstrong"); } }}fun main() { print("Nhap so co 3 chu so: ") val n = readLine()!!.trim().toInt()
val hundreds = n / 100 val tens = (n / 10) % 10 val ones = n % 10
val sum = hundreds * hundreds * hundreds + tens * tens * tens + ones * ones * ones println(if (sum == n) "La so Armstrong" else "Khong phai so Armstrong")}import 'dart:io';
void main() { stdout.write("Nhap so co 3 chu so: "); int n = int.parse(stdin.readLineSync()!);
int hundreds = n ~/ 100; int tens = (n ~/ 10) % 10; int ones = n % 10;
int sum = hundreds * hundreds * hundreds + tens * tens * tens + ones * ones * ones; print(sum == n ? "La so Armstrong" : "Khong phai so Armstrong");}38. break và continue
Đọc vào n, in ra các số từ 1 đến n, bỏ qua các số chia hết cho 3, và dừng hẳn khi gặp số chia hết cho 7.
Xem đáp án
while True: try: n = int(input("Nhập n: ")) break except ValueError: print("Vui lòng nhập một số nguyên hợp lệ!")
for i in range(1, n + 1): if i % 7 == 0: break if i % 3 == 0: continue print(i)#include <iostream>using namespace std;
int main() { int n; cout << "Nhap n: "; cin >> n;
for (int i = 1; i <= n; i++) { if (i % 7 == 0) break; if (i % 3 == 0) continue; cout << i << endl; } return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Nhap n: "); int n = Integer.parseInt(scanner.nextLine().trim());
for (int i = 1; i <= n; i++) { if (i % 7 == 0) break; if (i % 3 == 0) continue; System.out.println(i); } }}fun main() { print("Nhap n: ") val n = readLine()!!.trim().toInt()
for (i in 1..n) { if (i % 7 == 0) break if (i % 3 == 0) continue println(i) }}import 'dart:io';
void main() { stdout.write("Nhap n: "); int n = int.parse(stdin.readLineSync()!);
for (int i = 1; i <= n; i++) { if (i % 7 == 0) break; if (i % 3 == 0) continue; print(i); }}39. Vòng lặp lồng nhau - in ma trận số
Đọc vào n, in ra ma trận vuông kích thước n x n chứa các số từ 1 đến n*n, theo hàng.
Ví dụ n = 3:
1 2 34 5 67 8 9Xem đáp án
while True: try: n = int(input("Nhập n: ")) break except ValueError: print("Vui lòng nhập một số nguyên hợp lệ!")
num = 1for row in range(n): for col in range(n): print(num, end=" ") num += 1 print()#include <iostream>using namespace std;
int main() { int n; cout << "Nhap n: "; cin >> n;
int num = 1; for (int row = 0; row < n; row++) { for (int col = 0; col < n; col++) { cout << num << " "; num++; } cout << endl; } return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Nhap n: "); int n = Integer.parseInt(scanner.nextLine().trim());
int num = 1; for (int row = 0; row < n; row++) { for (int col = 0; col < n; col++) { System.out.print(num + " "); num++; } System.out.println(); } }}fun main() { print("Nhap n: ") val n = readLine()!!.trim().toInt()
var num = 1 for (row in 0 until n) { for (col in 0 until n) { print("$num ") num++ } println() }}import 'dart:io';
void main() { stdout.write("Nhap n: "); int n = int.parse(stdin.readLineSync()!);
int num = 1; for (int row = 0; row < n; row++) { for (int col = 0; col < n; col++) { stdout.write("$num "); num++; } print(""); }}40. Số nguyên tố cùng nhau
Đọc vào 2 số a, b. Kiểm tra chúng có phải là 2 số nguyên tố cùng nhau không (ƯCLN bằng 1).
Ví dụ:
Input: a=8, b=9Output: Nguyên tố cùng nhauXem đáp án
while True: try: a = int(input("a: ")) break except ValueError: print("Vui lòng nhập một số nguyên hợp lệ!")
while True: try: b = int(input("b: ")) break except ValueError: print("Vui lòng nhập một số nguyên hợp lệ!")
x, y = a, bwhile y != 0: x, y = y, x % y
print("Nguyên tố cùng nhau" if x == 1 else "Không phải nguyên tố cùng nhau")#include <iostream>using namespace std;
int main() { int a, b; cout << "a: "; cin >> a; cout << "b: "; cin >> b;
int x = a, y = b; while (y != 0) { int temp = y; y = x % y; x = temp; }
cout << (x == 1 ? "Nguyen to cung nhau" : "Khong phai nguyen to cung nhau") << endl; return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("a: "); int a = Integer.parseInt(scanner.nextLine().trim()); System.out.print("b: "); int b = Integer.parseInt(scanner.nextLine().trim());
int x = a, y = b; while (y != 0) { int temp = y; y = x % y; x = temp; }
System.out.println(x == 1 ? "Nguyen to cung nhau" : "Khong phai nguyen to cung nhau"); }}fun main() { print("a: ") val a = readLine()!!.trim().toInt() print("b: ") val b = readLine()!!.trim().toInt()
var x = a var y = b while (y != 0) { val temp = y y = x % y x = temp }
println(if (x == 1) "Nguyen to cung nhau" else "Khong phai nguyen to cung nhau")}import 'dart:io';
void main() { stdout.write("a: "); int a = int.parse(stdin.readLineSync()!); stdout.write("b: "); int b = int.parse(stdin.readLineSync()!);
int x = a, y = b; while (y != 0) { int temp = y; y = x % y; x = temp; }
print(x == 1 ? "Nguyen to cung nhau" : "Khong phai nguyen to cung nhau");}Nhóm 4: Chuỗi (String)
Phần tiêu đề “Nhóm 4: Chuỗi (String)”Xem thêm lý thuyết: Chuỗi ký tự (String), Các phương thức của String.
41. Đếm số ký tự trong chuỗi
Đọc vào một chuỗi, in ra độ dài của chuỗi đó (không dùng len()).
Xem đáp án
s = input("Nhập chuỗi: ")count = 0for _ in s: count += 1
print(count)#include <iostream>using namespace std;
int main() { string s; cout << "Nhap chuoi: "; getline(cin, s);
int count = 0; for (char c : s) { count++; }
cout << count << endl; return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Nhap chuoi: "); String s = scanner.nextLine();
int count = 0; for (char c : s.toCharArray()) { count++; }
System.out.println(count); }}fun main() { print("Nhap chuoi: ") val s = readLine()!!
var count = 0 for (c in s) { count++ }
println(count)}import 'dart:io';
void main() { stdout.write("Nhap chuoi: "); String s = stdin.readLineSync()!;
int count = 0; for (int i = 0; i < s.length; i++) { count++; }
print(count);}42. Đảo ngược chuỗi
Đọc vào một chuỗi, in ra chuỗi đó khi đảo ngược thứ tự ký tự.
Xem đáp án
s = input("Nhập chuỗi: ")print(s[::-1])#include <iostream>#include <algorithm>using namespace std;
int main() { string s; cout << "Nhap chuoi: "; getline(cin, s);
reverse(s.begin(), s.end()); cout << s << endl; return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Nhap chuoi: "); String s = scanner.nextLine();
System.out.println(new StringBuilder(s).reverse().toString()); }}fun main() { print("Nhap chuoi: ") val s = readLine()!!
println(s.reversed())}import 'dart:io';
void main() { stdout.write("Nhap chuoi: "); String s = stdin.readLineSync()!;
print(String.fromCharCodes(s.runes.toList().reversed));}43. Kiểm tra chuỗi đối xứng (Palindrome)
Palindrome (chuỗi đối xứng) là chuỗi khi đọc xuôi và đọc ngược đều giống nhau, ví dụ level, radar, hay madam. Đọc vào một chuỗi, kiểm tra chuỗi đó có phải là palindrome hay không.
Ví dụ:
Input: levelOutput: Là palindromeXem đáp án
s = input("Nhập chuỗi: ")print("Là palindrome" if s == s[::-1] else "Không phải palindrome")#include <iostream>#include <algorithm>using namespace std;
int main() { string s; cout << "Nhap chuoi: "; getline(cin, s);
string reversed = s; reverse(reversed.begin(), reversed.end());
cout << (s == reversed ? "La palindrome" : "Khong phai palindrome") << endl; return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Nhap chuoi: "); String s = scanner.nextLine();
String reversed = new StringBuilder(s).reverse().toString(); System.out.println(s.equals(reversed) ? "La palindrome" : "Khong phai palindrome"); }}fun main() { print("Nhap chuoi: ") val s = readLine()!!
println(if (s == s.reversed()) "La palindrome" else "Khong phai palindrome")}import 'dart:io';
void main() { stdout.write("Nhap chuoi: "); String s = stdin.readLineSync()!;
String reversed = String.fromCharCodes(s.runes.toList().reversed); print(s == reversed ? "La palindrome" : "Khong phai palindrome");}44. Đếm số nguyên âm và phụ âm
Đọc vào một chuỗi, đếm số lượng nguyên âm (a, e, i, o, u) có trong chuỗi (không phân biệt hoa thường).
Ví dụ:
Input: Hello WorldOutput: 3Xem đáp án
s = input("Nhập chuỗi: ").lower()vowels = "aeiou"count = 0
for c in s: if c in vowels: count += 1
print(count)#include <iostream>using namespace std;
int main() { string s; cout << "Nhap chuoi: "; getline(cin, s);
string vowels = "aeiou"; int count = 0; for (char c : s) { c = tolower(c); if (vowels.find(c) != string::npos) count++; }
cout << count << endl; return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Nhap chuoi: "); String s = scanner.nextLine().toLowerCase();
String vowels = "aeiou"; int count = 0; for (char c : s.toCharArray()) { if (vowels.indexOf(c) != -1) count++; }
System.out.println(count); }}fun main() { print("Nhap chuoi: ") val s = readLine()!!.lowercase()
val vowels = "aeiou" var count = 0 for (c in s) { if (c in vowels) count++ }
println(count)}import 'dart:io';
void main() { stdout.write("Nhap chuoi: "); String s = stdin.readLineSync()!.toLowerCase();
String vowels = "aeiou"; int count = 0; for (int i = 0; i < s.length; i++) { if (vowels.contains(s[i])) count++; }
print(count);}45. Viết hoa chữ cái đầu mỗi từ
Đọc vào một câu, in ra câu đó với chữ cái đầu mỗi từ được viết hoa (không dùng .title()).
Ví dụ:
Input: toi yeu pythonOutput: Toi Yeu PythonXem đáp án
s = input("Nhập câu: ")words = s.split()result = []
for word in words: result.append(word[0].upper() + word[1:])
print(" ".join(result))#include <iostream>#include <sstream>#include <cctype>using namespace std;
int main() { string s; cout << "Nhap cau: "; getline(cin, s);
stringstream ss(s); string word, result; while (ss >> word) { word[0] = toupper(word[0]); if (!result.empty()) result += " "; result += word; }
cout << result << endl; return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Nhap cau: "); String s = scanner.nextLine();
String[] words = s.split(" "); StringBuilder result = new StringBuilder(); for (String word : words) { if (result.length() > 0) result.append(" "); result.append(Character.toUpperCase(word.charAt(0))).append(word.substring(1)); }
System.out.println(result); }}fun main() { print("Nhap cau: ") val s = readLine()!!
val result = s.split(" ").joinToString(" ") { word -> word.replaceFirstChar { it.uppercase() } }
println(result)}import 'dart:io';
void main() { stdout.write("Nhap cau: "); String s = stdin.readLineSync()!;
String result = s.split(" ").map((word) { return word[0].toUpperCase() + word.substring(1); }).join(" ");
print(result);}46. Đếm số lần xuất hiện của 1 ký tự
Đọc vào một chuỗi và một ký tự, đếm xem ký tự đó xuất hiện bao nhiêu lần trong chuỗi.
Ví dụ:
Input: s=banana, c=aOutput: 3Xem đáp án
s = input("Nhập chuỗi: ")c = input("Nhập ký tự cần đếm: ")print(s.count(c))#include <iostream>using namespace std;
int main() { string s; char c; cout << "Nhap chuoi: "; getline(cin, s); cout << "Nhap ky tu can dem: "; cin >> c;
int count = 0; for (char ch : s) { if (ch == c) count++; }
cout << count << endl; return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Nhap chuoi: "); String s = scanner.nextLine(); System.out.print("Nhap ky tu can dem: "); char c = scanner.nextLine().trim().charAt(0);
int count = 0; for (char ch : s.toCharArray()) { if (ch == c) count++; }
System.out.println(count); }}fun main() { print("Nhap chuoi: ") val s = readLine()!! print("Nhap ky tu can dem: ") val c = readLine()!!.trim()[0]
println(s.count { it == c })}import 'dart:io';
void main() { stdout.write("Nhap chuoi: "); String s = stdin.readLineSync()!; stdout.write("Nhap ky tu can dem: "); String c = stdin.readLineSync()!.trim();
int count = s.split("").where((ch) => ch == c).length; print(count);}47. Loại bỏ khoảng trắng thừa
Đọc vào một chuỗi có nhiều khoảng trắng liên tiếp, in ra chuỗi chỉ còn 1 khoảng trắng giữa các từ.
Ví dụ:
Input: " hello world "Output: "hello world"Xem đáp án
s = input("Nhập chuỗi: ")print(" ".join(s.split()))#include <iostream>#include <sstream>using namespace std;
int main() { string s; cout << "Nhap chuoi: "; getline(cin, s);
stringstream ss(s); string word, result; while (ss >> word) { if (!result.empty()) result += " "; result += word; }
cout << result << endl; return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Nhap chuoi: "); String s = scanner.nextLine();
String result = String.join(" ", s.trim().split("\\s+")); System.out.println(result); }}fun main() { print("Nhap chuoi: ") val s = readLine()!!
val result = s.trim().split(Regex("\\s+")).joinToString(" ") println(result)}import 'dart:io';
void main() { stdout.write("Nhap chuoi: "); String s = stdin.readLineSync()!;
String result = s.trim().split(RegExp(r'\s+')).join(" "); print(result);}48. Kiểm tra Anagram
Anagram là 2 chuỗi được tạo từ cùng một tập ký tự nhưng sắp xếp theo thứ tự khác nhau, ví dụ listen và silent. Đọc vào 2 chuỗi, kiểm tra chúng có phải là anagram của nhau không.
Ví dụ:
Input: s1=listen, s2=silentOutput: Là anagramXem đáp án
s1 = input("Chuỗi 1: ").replace(" ", "").lower()s2 = input("Chuỗi 2: ").replace(" ", "").lower()
print("Là anagram" if sorted(s1) == sorted(s2) else "Không phải anagram")#include <iostream>#include <algorithm>using namespace std;
string normalize(string s) { string result; for (char c : s) { if (c != ' ') result += tolower(c); } sort(result.begin(), result.end()); return result;}
int main() { string s1, s2; cout << "Chuoi 1: "; getline(cin, s1); cout << "Chuoi 2: "; getline(cin, s2);
cout << (normalize(s1) == normalize(s2) ? "La anagram" : "Khong phai anagram") << endl; return 0;}import java.util.Arrays;import java.util.Scanner;
public class Main { static String normalize(String s) { char[] chars = s.replace(" ", "").toLowerCase().toCharArray(); Arrays.sort(chars); return new String(chars); }
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Chuoi 1: "); String s1 = scanner.nextLine(); System.out.print("Chuoi 2: "); String s2 = scanner.nextLine();
System.out.println(normalize(s1).equals(normalize(s2)) ? "La anagram" : "Khong phai anagram"); }}fun normalize(s: String) = s.replace(" ", "").lowercase().toList().sorted()
fun main() { print("Chuoi 1: ") val s1 = readLine()!! print("Chuoi 2: ") val s2 = readLine()!!
println(if (normalize(s1) == normalize(s2)) "La anagram" else "Khong phai anagram")}import 'dart:io';
List<String> normalize(String s) { List<String> chars = s.replaceAll(" ", "").toLowerCase().split(""); chars.sort(); return chars;}
void main() { stdout.write("Chuoi 1: "); String s1 = stdin.readLineSync()!; stdout.write("Chuoi 2: "); String s2 = stdin.readLineSync()!;
bool isAnagram = normalize(s1).join() == normalize(s2).join(); print(isAnagram ? "La anagram" : "Khong phai anagram");}49. Tìm từ dài nhất trong câu
Đọc vào một câu, in ra từ dài nhất trong câu đó.
Ví dụ:
Input: Hoc lap trinh rat thu viOutput: trinhXem đáp án
s = input("Nhập câu: ")words = s.split()
longest_word = words[0]for word in words: if len(word) > len(longest_word): longest_word = word
print(longest_word)#include <iostream>#include <sstream>using namespace std;
int main() { string s; cout << "Nhap cau: "; getline(cin, s);
stringstream ss(s); string word, longestWord; while (ss >> word) { if (word.length() > longestWord.length()) { longestWord = word; } }
cout << longestWord << endl; return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Nhap cau: "); String s = scanner.nextLine();
String[] words = s.split(" "); String longestWord = words[0]; for (String word : words) { if (word.length() > longestWord.length()) { longestWord = word; } }
System.out.println(longestWord); }}fun main() { print("Nhap cau: ") val s = readLine()!! val words = s.split(" ")
val longestWord = words.maxByOrNull { it.length } println(longestWord)}import 'dart:io';
void main() { stdout.write("Nhap cau: "); String s = stdin.readLineSync()!; List<String> words = s.split(" ");
String longestWord = words[0]; for (String word in words) { if (word.length > longestWord.length) { longestWord = word; } }
print(longestWord);}50. Thay thế ký tự trong chuỗi
Đọc vào một chuỗi, thay tất cả các ký tự "a" bằng "@" (không dùng .replace()).
Ví dụ:
Input: bananaOutput: b@n@n@Xem đáp án
s = input("Nhập chuỗi: ")result = ""
for c in s: if c == "a": result += "@" else: result += c
print(result)#include <iostream>using namespace std;
int main() { string s; cout << "Nhap chuoi: "; getline(cin, s);
string result; for (char c : s) { if (c == 'a') { result += '@'; } else { result += c; } }
cout << result << endl; return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Nhap chuoi: "); String s = scanner.nextLine();
StringBuilder result = new StringBuilder(); for (char c : s.toCharArray()) { result.append(c == 'a' ? '@' : c); }
System.out.println(result); }}fun main() { print("Nhap chuoi: ") val s = readLine()!!
val result = StringBuilder() for (c in s) { result.append(if (c == 'a') '@' else c) }
println(result)}import 'dart:io';
void main() { stdout.write("Nhap chuoi: "); String s = stdin.readLineSync()!;
String result = ""; for (int i = 0; i < s.length; i++) { result += s[i] == "a" ? "@" : s[i]; }
print(result);}51. Nối chuỗi từ danh sách
Cho một list các từ, ví dụ ["Toi", "yeu", "Python"]. In ra thành một câu, các từ cách nhau bởi dấu cách.
Xem đáp án
words = ["Toi", "yeu", "Python"]print(" ".join(words))#include <iostream>#include <vector>using namespace std;
int main() { vector<string> words = {"Toi", "yeu", "Python"};
string result; for (size_t i = 0; i < words.size(); i++) { if (i > 0) result += " "; result += words[i]; }
cout << result << endl; return 0;}import java.util.List;
public class Main { public static void main(String[] args) { List<String> words = List.of("Toi", "yeu", "Python"); System.out.println(String.join(" ", words)); }}fun main() { val words = listOf("Toi", "yeu", "Python") println(words.joinToString(" "))}void main() { List<String> words = ["Toi", "yeu", "Python"]; print(words.join(" "));}52. Đếm số từ trong câu
Đọc vào một câu, đếm số lượng từ trong câu đó.
Ví dụ:
Input: Toi dang hoc PythonOutput: 4Xem đáp án
s = input("Nhập câu: ")print(len(s.split()))#include <iostream>#include <sstream>using namespace std;
int main() { string s; cout << "Nhap cau: "; getline(cin, s);
stringstream ss(s); string word; int count = 0; while (ss >> word) count++;
cout << count << endl; return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Nhap cau: "); String s = scanner.nextLine();
System.out.println(s.trim().split("\\s+").length); }}fun main() { print("Nhap cau: ") val s = readLine()!!
println(s.trim().split(Regex("\\s+")).size)}import 'dart:io';
void main() { stdout.write("Nhap cau: "); String s = stdin.readLineSync()!;
print(s.trim().split(RegExp(r'\s+')).length);}53. Kiểm tra chuỗi con
Đọc vào chuỗi s và chuỗi sub. Kiểm tra sub có phải là chuỗi con của s hay không.
Ví dụ:
Input: s=hello world, sub=lo woOutput: Có chứaXem đáp án
s = input("Chuỗi gốc: ")sub = input("Chuỗi con cần tìm: ")
print("Có chứa" if sub in s else "Không chứa")#include <iostream>using namespace std;
int main() { string s, sub; cout << "Chuoi goc: "; getline(cin, s); cout << "Chuoi con can tim: "; getline(cin, sub);
cout << (s.find(sub) != string::npos ? "Co chua" : "Khong chua") << endl; return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Chuoi goc: "); String s = scanner.nextLine(); System.out.print("Chuoi con can tim: "); String sub = scanner.nextLine();
System.out.println(s.contains(sub) ? "Co chua" : "Khong chua"); }}fun main() { print("Chuoi goc: ") val s = readLine()!! print("Chuoi con can tim: ") val sub = readLine()!!
println(if (s.contains(sub)) "Co chua" else "Khong chua")}import 'dart:io';
void main() { stdout.write("Chuoi goc: "); String s = stdin.readLineSync()!; stdout.write("Chuoi con can tim: "); String sub = stdin.readLineSync()!;
print(s.contains(sub) ? "Co chua" : "Khong chua");}54. Chuyển đổi hoa/thường
Đọc vào một chuỗi, in ra chuỗi đó với mọi ký tự thường thành hoa và ngược lại (không dùng .swapcase()).
Ví dụ:
Input: Hello World 123Output: hELLO wORLD 123Xem đáp án
s = input("Nhập chuỗi: ")result = ""
for c in s: if c.isupper(): result += c.lower() elif c.islower(): result += c.upper() else: result += c
print(result)#include <iostream>#include <cctype>using namespace std;
int main() { string s; cout << "Nhap chuoi: "; getline(cin, s);
string result; for (char c : s) { if (isupper(c)) { result += tolower(c); } else if (islower(c)) { result += toupper(c); } else { result += c; } }
cout << result << endl; return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Nhap chuoi: "); String s = scanner.nextLine();
StringBuilder result = new StringBuilder(); for (char c : s.toCharArray()) { if (Character.isUpperCase(c)) { result.append(Character.toLowerCase(c)); } else if (Character.isLowerCase(c)) { result.append(Character.toUpperCase(c)); } else { result.append(c); } }
System.out.println(result); }}fun main() { print("Nhap chuoi: ") val s = readLine()!!
val result = StringBuilder() for (c in s) { when { c.isUpperCase() -> result.append(c.lowercaseChar()) c.isLowerCase() -> result.append(c.uppercaseChar()) else -> result.append(c) } }
println(result)}import 'dart:io';
void main() { stdout.write("Nhap chuoi: "); String s = stdin.readLineSync()!;
String result = ""; for (int i = 0; i < s.length; i++) { String c = s[i]; if (c == c.toUpperCase() && c != c.toLowerCase()) { result += c.toLowerCase(); } else if (c == c.toLowerCase() && c != c.toUpperCase()) { result += c.toUpperCase(); } else { result += c; } }
print(result);}55. Mã hóa Caesar đơn giản
Đọc vào một chuỗi chỉ gồm chữ thường và một số k. Mã hóa chuỗi bằng cách dịch mỗi ký tự đi k vị trí trong bảng chữ cái (chỉ xử lý 26 chữ cái a-z, có vòng lại từ đầu).
Ví dụ:
Input: s=abc, k=3Output: defXem đáp án
s = input("Nhập chuỗi (chữ thường): ")
while True: try: k = int(input("Nhập k: ")) break except ValueError: print("Vui lòng nhập một số nguyên hợp lệ!")
result = ""for c in s: # Dịch chuyển vị trí trong bảng chữ cái, dùng % 26 để vòng lại từ đầu new_position = (ord(c) - ord('a') + k) % 26 result += chr(new_position + ord('a'))
print(result)#include <iostream>using namespace std;
int main() { string s; int k; cout << "Nhap chuoi (chu thuong): "; cin >> s; cout << "Nhap k: "; cin >> k;
string result; for (char c : s) { int newPosition = (c - 'a' + k) % 26; result += (char)(newPosition + 'a'); }
cout << result << endl; return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Nhap chuoi (chu thuong): "); String s = scanner.nextLine().trim(); System.out.print("Nhap k: "); int k = Integer.parseInt(scanner.nextLine().trim());
StringBuilder result = new StringBuilder(); for (char c : s.toCharArray()) { int newPosition = (c - 'a' + k) % 26; result.append((char) (newPosition + 'a')); }
System.out.println(result); }}fun main() { print("Nhap chuoi (chu thuong): ") val s = readLine()!!.trim() print("Nhap k: ") val k = readLine()!!.trim().toInt()
val result = StringBuilder() for (c in s) { val newPosition = (c - 'a' + k) % 26 result.append(('a' + newPosition)) }
println(result)}import 'dart:io';
void main() { stdout.write("Nhap chuoi (chu thuong): "); String s = stdin.readLineSync()!.trim(); stdout.write("Nhap k: "); int k = int.parse(stdin.readLineSync()!);
String result = ""; for (int i = 0; i < s.length; i++) { int newPosition = (s.codeUnitAt(i) - 97 + k) % 26; result += String.fromCharCode(newPosition + 97); }
print(result);}Nhóm 5: List
Phần tiêu đề “Nhóm 5: List”Xem thêm lý thuyết: Danh sách (List).
56. Tính tổng và trung bình cộng của list
Cho một list số, tính tổng và trung bình cộng các phần tử.
Xem đáp án
numbers = [4, 8, 15, 16, 23, 42]total = sum(numbers)average = total / len(numbers)
print("Tổng:", total)print("Trung bình:", average)#include <iostream>#include <vector>using namespace std;
int main() { vector<int> numbers = {4, 8, 15, 16, 23, 42};
int total = 0; for (int n : numbers) total += n; double average = (double)total / numbers.size();
cout << "Tong: " << total << endl; cout << "Trung binh: " << average << endl; return 0;}public class Main { public static void main(String[] args) { int[] numbers = {4, 8, 15, 16, 23, 42};
int total = 0; for (int n : numbers) total += n; double average = (double) total / numbers.length;
System.out.println("Tong: " + total); System.out.println("Trung binh: " + average); }}fun main() { val numbers = listOf(4, 8, 15, 16, 23, 42)
val total = numbers.sum() val average = total.toDouble() / numbers.size
println("Tong: $total") println("Trung binh: $average")}void main() { List<int> numbers = [4, 8, 15, 16, 23, 42];
int total = numbers.reduce((a, b) => a + b); double average = total / numbers.length;
print("Tong: $total"); print("Trung binh: $average");}57. Tìm số lớn nhất, nhỏ nhất trong list
Cho một list số, tìm giá trị lớn nhất và nhỏ nhất (không dùng max(), min()).
Ví dụ:
Input: [4, 8, 15, 16, 23, 42]Output: Lớn nhất: 42, Nhỏ nhất: 4Xem đáp án
numbers = [4, 8, 15, 16, 23, 42]
largest = numbers[0]smallest = numbers[0]
for n in numbers: if n > largest: largest = n if n < smallest: smallest = n
print("Lớn nhất:", largest)print("Nhỏ nhất:", smallest)#include <iostream>#include <vector>using namespace std;
int main() { vector<int> numbers = {4, 8, 15, 16, 23, 42};
int largest = numbers[0]; int smallest = numbers[0];
for (int n : numbers) { if (n > largest) largest = n; if (n < smallest) smallest = n; }
cout << "Lon nhat: " << largest << endl; cout << "Nho nhat: " << smallest << endl; return 0;}public class Main { public static void main(String[] args) { int[] numbers = {4, 8, 15, 16, 23, 42};
int largest = numbers[0]; int smallest = numbers[0];
for (int n : numbers) { if (n > largest) largest = n; if (n < smallest) smallest = n; }
System.out.println("Lon nhat: " + largest); System.out.println("Nho nhat: " + smallest); }}fun main() { val numbers = listOf(4, 8, 15, 16, 23, 42)
var largest = numbers[0] var smallest = numbers[0]
for (n in numbers) { if (n > largest) largest = n if (n < smallest) smallest = n }
println("Lon nhat: $largest") println("Nho nhat: $smallest")}void main() { List<int> numbers = [4, 8, 15, 16, 23, 42];
int largest = numbers[0]; int smallest = numbers[0];
for (int n in numbers) { if (n > largest) largest = n; if (n < smallest) smallest = n; }
print("Lon nhat: $largest"); print("Nho nhat: $smallest");}58. Đảo ngược list
Cho một list, in ra list đó theo thứ tự đảo ngược (không dùng .reverse() hoặc [::-1]).
Xem đáp án
numbers = [1, 2, 3, 4, 5]result = []
for i in range(len(numbers) - 1, -1, -1): result.append(numbers[i])
print(result)#include <iostream>#include <vector>using namespace std;
int main() { vector<int> numbers = {1, 2, 3, 4, 5}; vector<int> result;
for (int i = numbers.size() - 1; i >= 0; i--) { result.push_back(numbers[i]); }
for (int n : result) cout << n << " "; cout << endl; return 0;}import java.util.ArrayList;import java.util.List;
public class Main { public static void main(String[] args) { int[] numbers = {1, 2, 3, 4, 5}; List<Integer> result = new ArrayList<>();
for (int i = numbers.length - 1; i >= 0; i--) { result.add(numbers[i]); }
System.out.println(result); }}fun main() { val numbers = listOf(1, 2, 3, 4, 5) val result = mutableListOf<Int>()
for (i in numbers.indices.reversed()) { result.add(numbers[i]) }
println(result)}void main() { List<int> numbers = [1, 2, 3, 4, 5]; List<int> result = [];
for (int i = numbers.length - 1; i >= 0; i--) { result.add(numbers[i]); }
print(result);}59. Loại bỏ phần tử trùng lặp
Cho một list có phần tử trùng lặp, tạo ra một list mới không có phần tử trùng, giữ nguyên thứ tự xuất hiện đầu tiên.
Ví dụ:
Input: [1, 2, 2, 3, 4, 4, 4, 5]Output: [1, 2, 3, 4, 5]Xem đáp án
numbers = [1, 2, 2, 3, 4, 4, 4, 5]result = []
for n in numbers: if n not in result: result.append(n)
print(result)#include <iostream>#include <vector>#include <algorithm>using namespace std;
int main() { vector<int> numbers = {1, 2, 2, 3, 4, 4, 4, 5}; vector<int> result;
for (int n : numbers) { if (find(result.begin(), result.end(), n) == result.end()) { result.push_back(n); } }
for (int n : result) cout << n << " "; cout << endl; return 0;}import java.util.ArrayList;import java.util.List;
public class Main { public static void main(String[] args) { int[] numbers = {1, 2, 2, 3, 4, 4, 4, 5}; List<Integer> result = new ArrayList<>();
for (int n : numbers) { if (!result.contains(n)) { result.add(n); } }
System.out.println(result); }}fun main() { val numbers = listOf(1, 2, 2, 3, 4, 4, 4, 5) val result = mutableListOf<Int>()
for (n in numbers) { if (n !in result) { result.add(n) } }
println(result)}void main() { List<int> numbers = [1, 2, 2, 3, 4, 4, 4, 5]; List<int> result = [];
for (int n in numbers) { if (!result.contains(n)) { result.add(n); } }
print(result);}60. Tìm số chẵn/lẻ trong list
Cho một list số nguyên, tạo ra 2 list mới chứa các số chẵn và các số lẻ.
Ví dụ:
Input: [1, 2, 3, 4, 5, 6, 7, 8]Output: Số chẵn: [2, 4, 6, 8], Số lẻ: [1, 3, 5, 7]Xem đáp án
numbers = [1, 2, 3, 4, 5, 6, 7, 8]even_numbers = []odd_numbers = []
for n in numbers: if n % 2 == 0: even_numbers.append(n) else: odd_numbers.append(n)
print("Số chẵn:", even_numbers)print("Số lẻ:", odd_numbers)#include <iostream>#include <vector>using namespace std;
int main() { vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8}; vector<int> evenNumbers, oddNumbers;
for (int n : numbers) { if (n % 2 == 0) evenNumbers.push_back(n); else oddNumbers.push_back(n); }
cout << "So chan: "; for (int n : evenNumbers) cout << n << " "; cout << endl << "So le: "; for (int n : oddNumbers) cout << n << " "; cout << endl; return 0;}import java.util.ArrayList;import java.util.List;
public class Main { public static void main(String[] args) { int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8}; List<Integer> evenNumbers = new ArrayList<>(); List<Integer> oddNumbers = new ArrayList<>();
for (int n : numbers) { if (n % 2 == 0) evenNumbers.add(n); else oddNumbers.add(n); }
System.out.println("So chan: " + evenNumbers); System.out.println("So le: " + oddNumbers); }}fun main() { val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8) val evenNumbers = mutableListOf<Int>() val oddNumbers = mutableListOf<Int>()
for (n in numbers) { if (n % 2 == 0) evenNumbers.add(n) else oddNumbers.add(n) }
println("So chan: $evenNumbers") println("So le: $oddNumbers")}void main() { List<int> numbers = [1, 2, 3, 4, 5, 6, 7, 8]; List<int> evenNumbers = []; List<int> oddNumbers = [];
for (int n in numbers) { if (n % 2 == 0) { evenNumbers.add(n); } else { oddNumbers.add(n); } }
print("So chan: $evenNumbers"); print("So le: $oddNumbers");}61. Sắp xếp list (Bubble Sort)
Bubble sort (sắp xếp nổi bọt) là thuật toán sắp xếp đơn giản: lặp lại việc so sánh 2 phần tử liền kề, nếu sai thứ tự thì đổi chỗ cho nhau, cứ thế đến khi không còn cặp nào cần đổi chỗ (giống bong bóng nổi dần lên trên). Cho một list số, sắp xếp tăng dần bằng thuật toán này, không dùng .sort().
Ví dụ:
Input: [5, 2, 9, 1, 5, 6]Output: [1, 2, 5, 5, 6, 9]Xem đáp án
numbers = [5, 2, 9, 1, 5, 6]n = len(numbers)
for i in range(n): for j in range(0, n - i - 1): if numbers[j] > numbers[j + 1]: numbers[j], numbers[j + 1] = numbers[j + 1], numbers[j]
print(numbers)#include <iostream>#include <vector>using namespace std;
int main() { vector<int> numbers = {5, 2, 9, 1, 5, 6}; int n = numbers.size();
for (int i = 0; i < n; i++) { for (int j = 0; j < n - i - 1; j++) { if (numbers[j] > numbers[j + 1]) { swap(numbers[j], numbers[j + 1]); } } }
for (int x : numbers) cout << x << " "; cout << endl; return 0;}public class Main { public static void main(String[] args) { int[] numbers = {5, 2, 9, 1, 5, 6}; int n = numbers.length;
for (int i = 0; i < n; i++) { for (int j = 0; j < n - i - 1; j++) { if (numbers[j] > numbers[j + 1]) { int temp = numbers[j]; numbers[j] = numbers[j + 1]; numbers[j + 1] = temp; } } }
for (int x : numbers) System.out.print(x + " "); }}fun main() { val numbers = intArrayOf(5, 2, 9, 1, 5, 6) val n = numbers.size
for (i in 0 until n) { for (j in 0 until n - i - 1) { if (numbers[j] > numbers[j + 1]) { val temp = numbers[j] numbers[j] = numbers[j + 1] numbers[j + 1] = temp } } }
println(numbers.joinToString(" "))}void main() { List<int> numbers = [5, 2, 9, 1, 5, 6]; int n = numbers.length;
for (int i = 0; i < n; i++) { for (int j = 0; j < n - i - 1; j++) { if (numbers[j] > numbers[j + 1]) { int temp = numbers[j]; numbers[j] = numbers[j + 1]; numbers[j + 1] = temp; } } }
print(numbers);}62. Tìm kiếm tuần tự (Linear Search)
Cho một list và một giá trị cần tìm, trả về vị trí (index) của giá trị đó trong list, hoặc -1 nếu không tìm thấy.
Ví dụ:
Input: numbers=[10, 25, 3, 47, 8], target=47Output: 3Xem đáp án
numbers = [10, 25, 3, 47, 8]target = 47
position = -1for i in range(len(numbers)): if numbers[i] == target: position = i break
print(position)#include <iostream>#include <vector>using namespace std;
int main() { vector<int> numbers = {10, 25, 3, 47, 8}; int target = 47;
int position = -1; for (int i = 0; i < (int)numbers.size(); i++) { if (numbers[i] == target) { position = i; break; } }
cout << position << endl; return 0;}public class Main { public static void main(String[] args) { int[] numbers = {10, 25, 3, 47, 8}; int target = 47;
int position = -1; for (int i = 0; i < numbers.length; i++) { if (numbers[i] == target) { position = i; break; } }
System.out.println(position); }}fun main() { val numbers = listOf(10, 25, 3, 47, 8) val target = 47
var position = -1 for (i in numbers.indices) { if (numbers[i] == target) { position = i break } }
println(position)}void main() { List<int> numbers = [10, 25, 3, 47, 8]; int target = 47;
int position = -1; for (int i = 0; i < numbers.length; i++) { if (numbers[i] == target) { position = i; break; } }
print(position);}63. Tính tổng 2 ma trận
Cho 2 ma trận (list 2 chiều) cùng kích thước, tính ma trận tổng.
Ví dụ:
Input: a=[[1,2],[3,4]], b=[[5,6],[7,8]]Output: [[6, 8], [10, 12]]Xem đáp án
a = [[1, 2], [3, 4]]b = [[5, 6], [7, 8]]
result = []for i in range(len(a)): row = [] for j in range(len(a[0])): row.append(a[i][j] + b[i][j]) result.append(row)
print(result)#include <iostream>#include <vector>using namespace std;
int main() { vector<vector<int>> a = {{1, 2}, {3, 4}}; vector<vector<int>> b = {{5, 6}, {7, 8}};
vector<vector<int>> result(a.size(), vector<int>(a[0].size())); for (size_t i = 0; i < a.size(); i++) { for (size_t j = 0; j < a[0].size(); j++) { result[i][j] = a[i][j] + b[i][j]; } }
for (auto& row : result) { for (int x : row) cout << x << " "; cout << endl; } return 0;}public class Main { public static void main(String[] args) { int[][] a = {{1, 2}, {3, 4}}; int[][] b = {{5, 6}, {7, 8}};
int[][] result = new int[a.length][a[0].length]; for (int i = 0; i < a.length; i++) { for (int j = 0; j < a[0].length; j++) { result[i][j] = a[i][j] + b[i][j]; } }
for (int[] row : result) { for (int x : row) System.out.print(x + " "); System.out.println(); } }}fun main() { val a = arrayOf(intArrayOf(1, 2), intArrayOf(3, 4)) val b = arrayOf(intArrayOf(5, 6), intArrayOf(7, 8))
val result = Array(a.size) { i -> IntArray(a[0].size) { j -> a[i][j] + b[i][j] } }
for (row in result) { println(row.joinToString(" ")) }}void main() { List<List<int>> a = [[1, 2], [3, 4]]; List<List<int>> b = [[5, 6], [7, 8]];
List<List<int>> result = []; for (int i = 0; i < a.length; i++) { List<int> row = []; for (int j = 0; j < a[0].length; j++) { row.add(a[i][j] + b[i][j]); } result.add(row); }
print(result);}64. Làm phẳng list lồng nhau
Cho một list chứa các list con, ví dụ [[1, 2], [3, 4], [5]]. In ra một list phẳng chứa tất cả phần tử.
Ví dụ:
Input: [[1, 2], [3, 4], [5]]Output: [1, 2, 3, 4, 5]Xem đáp án
matrix = [[1, 2], [3, 4], [5]]result = []
for row in matrix: for element in row: result.append(element)
print(result)#include <iostream>#include <vector>using namespace std;
int main() { vector<vector<int>> matrix = {{1, 2}, {3, 4}, {5}}; vector<int> result;
for (auto& row : matrix) { for (int element : row) { result.push_back(element); } }
for (int x : result) cout << x << " "; cout << endl; return 0;}import java.util.ArrayList;import java.util.List;
public class Main { public static void main(String[] args) { int[][] matrix = {{1, 2}, {3, 4}, {5}}; List<Integer> result = new ArrayList<>();
for (int[] row : matrix) { for (int element : row) { result.add(element); } }
System.out.println(result); }}fun main() { val matrix = listOf(listOf(1, 2), listOf(3, 4), listOf(5)) val result = mutableListOf<Int>()
for (row in matrix) { for (element in row) { result.add(element) } }
println(result)}void main() { List<List<int>> matrix = [[1, 2], [3, 4], [5]]; List<int> result = [];
for (List<int> row in matrix) { for (int element in row) { result.add(element); } }
print(result);}65. Trộn 2 list đã sắp xếp
Cho 2 list đã sắp xếp tăng dần, trộn chúng thành 1 list mới cũng tăng dần (không dùng sorted()).
Ví dụ:
Input: a=[1, 3, 5, 7], b=[2, 4, 6, 8, 10]Output: [1, 2, 3, 4, 5, 6, 7, 8, 10]Xem đáp án
a = [1, 3, 5, 7]b = [2, 4, 6, 8, 10]
result = []i, j = 0, 0
while i < len(a) and j < len(b): if a[i] <= b[j]: result.append(a[i]) i += 1 else: result.append(b[j]) j += 1
result.extend(a[i:])result.extend(b[j:])
print(result)#include <iostream>#include <vector>using namespace std;
int main() { vector<int> a = {1, 3, 5, 7}; vector<int> b = {2, 4, 6, 8, 10};
vector<int> result; size_t i = 0, j = 0;
while (i < a.size() && j < b.size()) { if (a[i] <= b[j]) result.push_back(a[i++]); else result.push_back(b[j++]); } while (i < a.size()) result.push_back(a[i++]); while (j < b.size()) result.push_back(b[j++]);
for (int x : result) cout << x << " "; cout << endl; return 0;}import java.util.ArrayList;import java.util.List;
public class Main { public static void main(String[] args) { int[] a = {1, 3, 5, 7}; int[] b = {2, 4, 6, 8, 10};
List<Integer> result = new ArrayList<>(); int i = 0, j = 0;
while (i < a.length && j < b.length) { if (a[i] <= b[j]) result.add(a[i++]); else result.add(b[j++]); } while (i < a.length) result.add(a[i++]); while (j < b.length) result.add(b[j++]);
System.out.println(result); }}fun main() { val a = listOf(1, 3, 5, 7) val b = listOf(2, 4, 6, 8, 10)
val result = mutableListOf<Int>() var i = 0 var j = 0
while (i < a.size && j < b.size) { if (a[i] <= b[j]) result.add(a[i++]) else result.add(b[j++]) } while (i < a.size) result.add(a[i++]) while (j < b.size) result.add(b[j++])
println(result)}void main() { List<int> a = [1, 3, 5, 7]; List<int> b = [2, 4, 6, 8, 10];
List<int> result = []; int i = 0, j = 0;
while (i < a.length && j < b.length) { if (a[i] <= b[j]) { result.add(a[i++]); } else { result.add(b[j++]); } } while (i < a.length) result.add(a[i++]); while (j < b.length) result.add(b[j++]);
print(result);}66. Tìm phần tử xuất hiện nhiều nhất
Cho một list, tìm phần tử xuất hiện nhiều lần nhất trong list đó.
Ví dụ:
Input: [1, 3, 2, 3, 4, 3, 2]Output: 3Xem đáp án
numbers = [1, 3, 2, 3, 4, 3, 2]
count = {}for n in numbers: count[n] = count.get(n, 0) + 1
most_frequent = max(count, key=count.get)print(most_frequent)#include <iostream>#include <vector>#include <unordered_map>using namespace std;
int main() { vector<int> numbers = {1, 3, 2, 3, 4, 3, 2};
unordered_map<int, int> count; for (int n : numbers) count[n]++;
int mostFrequent = numbers[0]; int maxCount = 0; for (auto& [key, value] : count) { if (value > maxCount) { maxCount = value; mostFrequent = key; } }
cout << mostFrequent << endl; return 0;}import java.util.HashMap;import java.util.Map;
public class Main { public static void main(String[] args) { int[] numbers = {1, 3, 2, 3, 4, 3, 2};
Map<Integer, Integer> count = new HashMap<>(); for (int n : numbers) { count.put(n, count.getOrDefault(n, 0) + 1); }
int mostFrequent = numbers[0]; int maxCount = 0; for (Map.Entry<Integer, Integer> entry : count.entrySet()) { if (entry.getValue() > maxCount) { maxCount = entry.getValue(); mostFrequent = entry.getKey(); } }
System.out.println(mostFrequent); }}fun main() { val numbers = listOf(1, 3, 2, 3, 4, 3, 2)
val count = mutableMapOf<Int, Int>() for (n in numbers) { count[n] = count.getOrDefault(n, 0) + 1 }
val mostFrequent = count.maxByOrNull { it.value }?.key println(mostFrequent)}void main() { List<int> numbers = [1, 3, 2, 3, 4, 3, 2];
Map<int, int> count = {}; for (int n in numbers) { count[n] = (count[n] ?? 0) + 1; }
int mostFrequent = numbers[0]; int maxCount = 0; count.forEach((key, value) { if (value > maxCount) { maxCount = value; mostFrequent = key; } });
print(mostFrequent);}67. Xoay list
Cho một list và một số k, xoay list sang phải k vị trí. Ví dụ [1,2,3,4,5] xoay 2 vị trí thành [4,5,1,2,3].
Ví dụ:
Input: numbers=[1, 2, 3, 4, 5], k=2Output: [4, 5, 1, 2, 3]Xem đáp án
numbers = [1, 2, 3, 4, 5]k = 2
k = k % len(numbers)result = numbers[-k:] + numbers[:-k]
print(result)#include <iostream>#include <vector>using namespace std;
int main() { vector<int> numbers = {1, 2, 3, 4, 5}; int k = 2; k = k % numbers.size();
vector<int> result; result.insert(result.end(), numbers.end() - k, numbers.end()); result.insert(result.end(), numbers.begin(), numbers.end() - k);
for (int x : result) cout << x << " "; cout << endl; return 0;}import java.util.ArrayList;import java.util.List;
public class Main { public static void main(String[] args) { int[] numbers = {1, 2, 3, 4, 5}; int k = 2 % numbers.length;
List<Integer> result = new ArrayList<>(); for (int i = numbers.length - k; i < numbers.length; i++) result.add(numbers[i]); for (int i = 0; i < numbers.length - k; i++) result.add(numbers[i]);
System.out.println(result); }}fun main() { val numbers = listOf(1, 2, 3, 4, 5) val k = 2 % numbers.size
val result = numbers.takeLast(k) + numbers.dropLast(k) println(result)}void main() { List<int> numbers = [1, 2, 3, 4, 5]; int k = 2 % numbers.length;
List<int> result = [ ...numbers.sublist(numbers.length - k), ...numbers.sublist(0, numbers.length - k), ];
print(result);}68. Kiểm tra list con
Cho 2 list a và b, kiểm tra tất cả phần tử của b có nằm trong a không.
Ví dụ:
Input: a=[1, 2, 3, 4, 5], b=[2, 4]Output: TrueXem đáp án
a = [1, 2, 3, 4, 5]b = [2, 4]
is_sublist = all(element in a for element in b)print(is_sublist)#include <iostream>#include <vector>#include <algorithm>using namespace std;
int main() { vector<int> a = {1, 2, 3, 4, 5}; vector<int> b = {2, 4};
bool isSublist = true; for (int element : b) { if (find(a.begin(), a.end(), element) == a.end()) { isSublist = false; break; } }
cout << (isSublist ? "true" : "false") << endl; return 0;}import java.util.Arrays;import java.util.List;
public class Main { public static void main(String[] args) { List<Integer> a = Arrays.asList(1, 2, 3, 4, 5); List<Integer> b = Arrays.asList(2, 4);
boolean isSublist = a.containsAll(b); System.out.println(isSublist); }}fun main() { val a = listOf(1, 2, 3, 4, 5) val b = listOf(2, 4)
val isSublist = a.containsAll(b) println(isSublist)}void main() { List<int> a = [1, 2, 3, 4, 5]; List<int> b = [2, 4];
bool isSublist = b.every((element) => a.contains(element)); print(isSublist);}69. Tính tổng đường chéo ma trận
Cho một ma trận vuông, tính tổng các phần tử trên đường chéo chính.
Ví dụ:
Input: [[1,2,3],[4,5,6],[7,8,9]]Output: 15Xem đáp án
matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9],]
total = 0for i in range(len(matrix)): total += matrix[i][i]
print(total)#include <iostream>#include <vector>using namespace std;
int main() { vector<vector<int>> matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, };
int total = 0; for (size_t i = 0; i < matrix.size(); i++) { total += matrix[i][i]; }
cout << total << endl; return 0;}public class Main { public static void main(String[] args) { int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, };
int total = 0; for (int i = 0; i < matrix.length; i++) { total += matrix[i][i]; }
System.out.println(total); }}fun main() { val matrix = arrayOf( intArrayOf(1, 2, 3), intArrayOf(4, 5, 6), intArrayOf(7, 8, 9), )
var total = 0 for (i in matrix.indices) { total += matrix[i][i] }
println(total)}void main() { List<List<int>> matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ];
int total = 0; for (int i = 0; i < matrix.length; i++) { total += matrix[i][i]; }
print(total);}70. Chia list thành các nhóm nhỏ
Cho một list và một số n, chia list thành các nhóm con có tối đa n phần tử.
Ví dụ:
Input: numbers=[1,2,3,4,5,6,7], n=3Output: [[1, 2, 3], [4, 5, 6], [7]]Xem đáp án
numbers = [1, 2, 3, 4, 5, 6, 7]n = 3
groups = []for i in range(0, len(numbers), n): groups.append(numbers[i:i + n])
print(groups)#include <iostream>#include <vector>using namespace std;
int main() { vector<int> numbers = {1, 2, 3, 4, 5, 6, 7}; int n = 3;
vector<vector<int>> groups; for (size_t i = 0; i < numbers.size(); i += n) { vector<int> group; for (size_t j = i; j < min(i + n, numbers.size()); j++) { group.push_back(numbers[j]); } groups.push_back(group); }
for (auto& group : groups) { for (int x : group) cout << x << " "; cout << endl; } return 0;}import java.util.ArrayList;import java.util.Arrays;import java.util.List;
public class Main { public static void main(String[] args) { Integer[] numbers = {1, 2, 3, 4, 5, 6, 7}; int n = 3;
List<List<Integer>> groups = new ArrayList<>(); for (int i = 0; i < numbers.length; i += n) { int end = Math.min(i + n, numbers.length); groups.add(Arrays.asList(numbers).subList(i, end)); }
System.out.println(groups); }}fun main() { val numbers = listOf(1, 2, 3, 4, 5, 6, 7) val n = 3
val groups = numbers.chunked(n) println(groups)}void main() { List<int> numbers = [1, 2, 3, 4, 5, 6, 7]; int n = 3;
List<List<int>> groups = []; for (int i = 0; i < numbers.length; i += n) { int end = (i + n < numbers.length) ? i + n : numbers.length; groups.add(numbers.sublist(i, end)); }
print(groups);}Nhóm 6: Tuple, Dictionary, Set
Phần tiêu đề “Nhóm 6: Tuple, Dictionary, Set”Xem thêm lý thuyết: Tuple, Từ điển (Dictionary), Tập hợp (Set).
71. Đổi list thành tuple và ngược lại
Cho một list, chuyển thành tuple; sau đó chuyển tuple đó ngược lại thành list.
Xem đáp án
numbers = [1, 2, 3]t = tuple(numbers)print(t)
l = list(t)print(l)#include <iostream>#include <vector>#include <tuple>using namespace std;
int main() { vector<int> numbers = {1, 2, 3}; auto t = make_tuple(numbers[0], numbers[1], numbers[2]); cout << "(" << get<0>(t) << ", " << get<1>(t) << ", " << get<2>(t) << ")" << endl;
vector<int> l = {get<0>(t), get<1>(t), get<2>(t)}; for (int x : l) cout << x << " "; cout << endl; return 0;}import java.util.List;import java.util.ArrayList;
public class Main { public static void main(String[] args) { List<Integer> numbers = List.of(1, 2, 3); // Java không có kiểu tuple sẵn có - dùng List bất biến (immutable) để mô phỏng List<Integer> t = List.copyOf(numbers); System.out.println(t);
List<Integer> l = new ArrayList<>(t); System.out.println(l); }}fun main() { val numbers = listOf(1, 2, 3) val t = Triple(numbers[0], numbers[1], numbers[2]) println(t)
val l = listOf(t.first, t.second, t.third) println(l)}void main() { List<int> numbers = [1, 2, 3]; var t = (numbers[0], numbers[1], numbers[2]); // Record - tuple của Dart 3 print(t);
List<int> l = [t.$1, t.$2, t.$3]; print(l);}72. Đếm số lần xuất hiện của từ (dictionary)
Đọc vào một câu, đếm số lần xuất hiện của mỗi từ, lưu vào dictionary.
Ví dụ:
Input: "con meo con cho con meo"Output: {'con': 3, 'meo': 2, 'cho': 1}Xem đáp án
s = input("Nhập câu: ")words = s.split()
count = {}for w in words: count[w] = count.get(w, 0) + 1
print(count)#include <iostream>#include <sstream>#include <map>using namespace std;
int main() { string s; cout << "Nhap cau: "; getline(cin, s);
stringstream ss(s); string word; map<string, int> count; while (ss >> word) { count[word]++; }
for (auto& [key, value] : count) { cout << key << ": " << value << endl; } return 0;}import java.util.LinkedHashMap;import java.util.Map;import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Nhap cau: "); String s = scanner.nextLine();
Map<String, Integer> count = new LinkedHashMap<>(); for (String word : s.split(" ")) { count.put(word, count.getOrDefault(word, 0) + 1); }
System.out.println(count); }}fun main() { print("Nhap cau: ") val s = readLine()!!
val count = mutableMapOf<String, Int>() for (word in s.split(" ")) { count[word] = count.getOrDefault(word, 0) + 1 }
println(count)}import 'dart:io';
void main() { stdout.write("Nhap cau: "); String s = stdin.readLineSync()!;
Map<String, int> count = {}; for (String word in s.split(" ")) { count[word] = (count[word] ?? 0) + 1; }
print(count);}73. Gộp 2 dictionary
Cho 2 dictionary, gộp chúng thành 1 dictionary mới. Nếu trùng key, lấy giá trị của dictionary thứ 2.
Ví dụ:
Input: a={"x": 1, "y": 2}, b={"y": 3, "z": 4}Output: {'x': 1, 'y': 3, 'z': 4}Xem đáp án
a = {"x": 1, "y": 2}b = {"y": 3, "z": 4}
result = {**a, **b}print(result)#include <iostream>#include <map>using namespace std;
int main() { map<string, int> a = {{"x", 1}, {"y", 2}}; map<string, int> b = {{"y", 3}, {"z", 4}};
map<string, int> result = a; for (auto& [key, value] : b) { result[key] = value; }
for (auto& [key, value] : result) { cout << key << ": " << value << endl; } return 0;}import java.util.LinkedHashMap;import java.util.Map;
public class Main { public static void main(String[] args) { Map<String, Integer> a = new LinkedHashMap<>(Map.of("x", 1, "y", 2)); Map<String, Integer> b = Map.of("y", 3, "z", 4);
Map<String, Integer> result = new LinkedHashMap<>(a); result.putAll(b);
System.out.println(result); }}fun main() { val a = mapOf("x" to 1, "y" to 2) val b = mapOf("y" to 3, "z" to 4)
val result = a + b println(result)}void main() { Map<String, int> a = {"x": 1, "y": 2}; Map<String, int> b = {"y": 3, "z": 4};
Map<String, int> result = {...a, ...b}; print(result);}74. Tìm key có giá trị lớn nhất trong dictionary
Cho một dictionary điểm số học sinh, ví dụ {"An": 8, "Binh": 9, "Chi": 7}. Tìm ra học sinh có điểm cao nhất.
Ví dụ:
Input: {"An": 8, "Binh": 9, "Chi": 7}Output: Binh 9Xem đáp án
score = {"An": 8, "Binh": 9, "Chi": 7}top_student = max(score, key=score.get)
print(top_student, score[top_student])#include <iostream>#include <map>using namespace std;
int main() { map<string, int> score = {{"An", 8}, {"Binh", 9}, {"Chi", 7}};
string topStudent; int maxScore = -1; for (auto& [name, s] : score) { if (s > maxScore) { maxScore = s; topStudent = name; } }
cout << topStudent << " " << maxScore << endl; return 0;}import java.util.Map;
public class Main { public static void main(String[] args) { Map<String, Integer> score = Map.of("An", 8, "Binh", 9, "Chi", 7);
String topStudent = null; int maxScore = -1; for (Map.Entry<String, Integer> entry : score.entrySet()) { if (entry.getValue() > maxScore) { maxScore = entry.getValue(); topStudent = entry.getKey(); } }
System.out.println(topStudent + " " + maxScore); }}fun main() { val score = mapOf("An" to 8, "Binh" to 9, "Chi" to 7)
val topStudent = score.maxByOrNull { it.value } println("${topStudent?.key} ${topStudent?.value}")}void main() { Map<String, int> score = {"An": 8, "Binh": 9, "Chi": 7};
String topStudent = ""; int maxScore = -1; score.forEach((name, s) { if (s > maxScore) { maxScore = s; topStudent = name; } });
print("$topStudent $maxScore");}75. Đảo ngược key-value của dictionary
Cho một dictionary, tạo ra dictionary mới với key và value bị đảo ngược cho nhau.
Ví dụ:
Input: {"a": 1, "b": 2, "c": 3}Output: {1: 'a', 2: 'b', 3: 'c'}Xem đáp án
d = {"a": 1, "b": 2, "c": 3}result = {value: key for key, value in d.items()}
print(result)#include <iostream>#include <map>using namespace std;
int main() { map<string, int> d = {{"a", 1}, {"b", 2}, {"c", 3}};
map<int, string> result; for (auto& [key, value] : d) { result[value] = key; }
for (auto& [key, value] : result) { cout << key << ": " << value << endl; } return 0;}import java.util.LinkedHashMap;import java.util.Map;
public class Main { public static void main(String[] args) { Map<String, Integer> d = new LinkedHashMap<>(Map.of("a", 1, "b", 2, "c", 3));
Map<Integer, String> result = new LinkedHashMap<>(); for (Map.Entry<String, Integer> entry : d.entrySet()) { result.put(entry.getValue(), entry.getKey()); }
System.out.println(result); }}fun main() { val d = mapOf("a" to 1, "b" to 2, "c" to 3)
val result = d.entries.associate { (key, value) -> value to key } println(result)}void main() { Map<String, int> d = {"a": 1, "b": 2, "c": 3};
Map<int, String> result = {}; d.forEach((key, value) { result[value] = key; });
print(result);}76. Giao và hợp của 2 set
Cho 2 set số nguyên, tìm giao (phần tử chung) và hợp (tất cả phần tử) của chúng.
Ví dụ:
Input: a={1,2,3,4}, b={3,4,5,6}Output: Giao: {3, 4}, Hợp: {1, 2, 3, 4, 5, 6}Xem đáp án
a = {1, 2, 3, 4}b = {3, 4, 5, 6}
print("Giao:", a & b)print("Hợp:", a | b)print("Hiệu (a - b):", a - b)#include <iostream>#include <set>#include <algorithm>#include <iterator>using namespace std;
int main() { set<int> a = {1, 2, 3, 4}; set<int> b = {3, 4, 5, 6};
set<int> intersection, unionSet, difference; set_intersection(a.begin(), a.end(), b.begin(), b.end(), inserter(intersection, intersection.begin())); set_union(a.begin(), a.end(), b.begin(), b.end(), inserter(unionSet, unionSet.begin())); set_difference(a.begin(), a.end(), b.begin(), b.end(), inserter(difference, difference.begin()));
cout << "Giao: "; for (int x : intersection) cout << x << " "; cout << endl << "Hop: "; for (int x : unionSet) cout << x << " "; cout << endl << "Hieu (a - b): "; for (int x : difference) cout << x << " "; cout << endl; return 0;}import java.util.LinkedHashSet;import java.util.Set;
public class Main { public static void main(String[] args) { Set<Integer> a = new LinkedHashSet<>(Set.of(1, 2, 3, 4)); Set<Integer> b = new LinkedHashSet<>(Set.of(3, 4, 5, 6));
Set<Integer> intersection = new LinkedHashSet<>(a); intersection.retainAll(b);
Set<Integer> union = new LinkedHashSet<>(a); union.addAll(b);
Set<Integer> difference = new LinkedHashSet<>(a); difference.removeAll(b);
System.out.println("Giao: " + intersection); System.out.println("Hop: " + union); System.out.println("Hieu (a - b): " + difference); }}fun main() { val a = setOf(1, 2, 3, 4) val b = setOf(3, 4, 5, 6)
println("Giao: ${a intersect b}") println("Hop: ${a union b}") println("Hieu (a - b): ${a subtract b}")}void main() { Set<int> a = {1, 2, 3, 4}; Set<int> b = {3, 4, 5, 6};
print("Giao: ${a.intersection(b)}"); print("Hop: ${a.union(b)}"); print("Hieu (a - b): ${a.difference(b)}");}77. Loại bỏ trùng lặp bằng set
Cho một list có phần tử trùng lặp, dùng set để loại bỏ trùng lặp, sau đó in ra dưới dạng list đã sắp xếp.
Ví dụ:
Input: [3, 1, 2, 3, 4, 1, 5]Output: [1, 2, 3, 4, 5]Xem đáp án
numbers = [3, 1, 2, 3, 4, 1, 5]result = sorted(set(numbers))
print(result)#include <iostream>#include <vector>#include <set>using namespace std;
int main() { vector<int> numbers = {3, 1, 2, 3, 4, 1, 5};
set<int> uniqueSet(numbers.begin(), numbers.end());
for (int x : uniqueSet) cout << x << " "; cout << endl; return 0;}import java.util.TreeSet;
public class Main { public static void main(String[] args) { int[] numbers = {3, 1, 2, 3, 4, 1, 5};
TreeSet<Integer> uniqueSet = new TreeSet<>(); for (int n : numbers) uniqueSet.add(n);
System.out.println(uniqueSet); }}fun main() { val numbers = listOf(3, 1, 2, 3, 4, 1, 5)
val result = numbers.toSortedSet() println(result)}void main() { List<int> numbers = [3, 1, 2, 3, 4, 1, 5];
List<int> result = numbers.toSet().toList()..sort(); print(result);}78. Danh bạ điện thoại đơn giản
Tạo một dictionary contacts lưu tên và số điện thoại. Viết chương trình cho phép thêm 1 người mới và in ra toàn bộ danh bạ.
Xem đáp án
contacts = {"An": "0901111111", "Binh": "0902222222"}
name = input("Tên người mới: ")phone = input("Số điện thoại: ")contacts[name] = phone
for name, phone in contacts.items(): print(f"{name}: {phone}")#include <iostream>#include <map>using namespace std;
int main() { map<string, string> contacts = {{"An", "0901111111"}, {"Binh", "0902222222"}};
string name, phone; cout << "Ten nguoi moi: "; getline(cin, name); cout << "So dien thoai: "; getline(cin, phone); contacts[name] = phone;
for (auto& [n, p] : contacts) { cout << n << ": " << p << endl; } return 0;}import java.util.LinkedHashMap;import java.util.Map;import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Map<String, String> contacts = new LinkedHashMap<>(); contacts.put("An", "0901111111"); contacts.put("Binh", "0902222222");
System.out.print("Ten nguoi moi: "); String name = scanner.nextLine(); System.out.print("So dien thoai: "); String phone = scanner.nextLine(); contacts.put(name, phone);
for (Map.Entry<String, String> entry : contacts.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } }}fun main() { val contacts = mutableMapOf("An" to "0901111111", "Binh" to "0902222222")
print("Ten nguoi moi: ") val name = readLine()!! print("So dien thoai: ") val phone = readLine()!! contacts[name] = phone
for ((n, p) in contacts) { println("$n: $p") }}import 'dart:io';
void main() { Map<String, String> contacts = {"An": "0901111111", "Binh": "0902222222"};
stdout.write("Ten nguoi moi: "); String name = stdin.readLineSync()!; stdout.write("So dien thoai: "); String phone = stdin.readLineSync()!; contacts[name] = phone;
contacts.forEach((n, p) { print("$n: $p"); });}79. Kiểm tra 2 tập hợp rời nhau
Cho 2 set, kiểm tra chúng có phần tử chung hay không (rời nhau nghĩa là không có phần tử chung).
Ví dụ:
Input: a={1,2,3}, b={4,5,6}Output: TrueXem đáp án
a = {1, 2, 3}b = {4, 5, 6}
print(a.isdisjoint(b))#include <iostream>#include <set>#include <algorithm>using namespace std;
int main() { set<int> a = {1, 2, 3}; set<int> b = {4, 5, 6};
set<int> intersection; set_intersection(a.begin(), a.end(), b.begin(), b.end(), inserter(intersection, intersection.begin()));
cout << (intersection.empty() ? "true" : "false") << endl; return 0;}import java.util.Set;import java.util.HashSet;
public class Main { public static void main(String[] args) { Set<Integer> a = Set.of(1, 2, 3); Set<Integer> b = Set.of(4, 5, 6);
Set<Integer> intersection = new HashSet<>(a); intersection.retainAll(b);
System.out.println(intersection.isEmpty()); }}fun main() { val a = setOf(1, 2, 3) val b = setOf(4, 5, 6)
println(a.intersect(b).isEmpty())}void main() { Set<int> a = {1, 2, 3}; Set<int> b = {4, 5, 6};
print(a.intersection(b).isEmpty);}80. Nhóm học sinh theo xếp loại (dictionary of list)
Cho một dictionary điểm học sinh, nhóm học sinh vào các loại “Giỏi” (>=8), “Khá” (>=6.5), “Trung bình” (còn lại).
Ví dụ:
Input: {"An": 9, "Binh": 7, "Chi": 5, "Dat": 6.8}Output: {'Gioi': ['An'], 'Kha': ['Dat'], 'Trung binh': ['Binh', 'Chi']}Xem đáp án
score = {"An": 9, "Binh": 7, "Chi": 5, "Dat": 6.8}groups = {"Gioi": [], "Kha": [], "Trung binh": []}
for name, d in score.items(): if d >= 8: groups["Gioi"].append(name) elif d >= 6.5: groups["Kha"].append(name) else: groups["Trung binh"].append(name)
print(groups)#include <iostream>#include <map>#include <vector>using namespace std;
int main() { map<string, double> score = {{"An", 9}, {"Binh", 7}, {"Chi", 5}, {"Dat", 6.8}}; map<string, vector<string>> groups = {{"Gioi", {}}, {"Kha", {}}, {"Trung binh", {}}};
for (auto& [name, d] : score) { if (d >= 8) groups["Gioi"].push_back(name); else if (d >= 6.5) groups["Kha"].push_back(name); else groups["Trung binh"].push_back(name); }
for (auto& [group, names] : groups) { cout << group << ": "; for (auto& n : names) cout << n << " "; cout << endl; } return 0;}import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;
public class Main { public static void main(String[] args) { Map<String, Double> score = new LinkedHashMap<>(); score.put("An", 9.0); score.put("Binh", 7.0); score.put("Chi", 5.0); score.put("Dat", 6.8);
Map<String, List<String>> groups = new LinkedHashMap<>(); groups.put("Gioi", new ArrayList<>()); groups.put("Kha", new ArrayList<>()); groups.put("Trung binh", new ArrayList<>());
for (Map.Entry<String, Double> entry : score.entrySet()) { double d = entry.getValue(); if (d >= 8) groups.get("Gioi").add(entry.getKey()); else if (d >= 6.5) groups.get("Kha").add(entry.getKey()); else groups.get("Trung binh").add(entry.getKey()); }
System.out.println(groups); }}fun main() { val score = linkedMapOf("An" to 9.0, "Binh" to 7.0, "Chi" to 5.0, "Dat" to 6.8) val groups = linkedMapOf("Gioi" to mutableListOf<String>(), "Kha" to mutableListOf(), "Trung binh" to mutableListOf())
for ((name, d) in score) { when { d >= 8 -> groups["Gioi"]!!.add(name) d >= 6.5 -> groups["Kha"]!!.add(name) else -> groups["Trung binh"]!!.add(name) } }
println(groups)}void main() { Map<String, double> score = {"An": 9, "Binh": 7, "Chi": 5, "Dat": 6.8}; Map<String, List<String>> groups = {"Gioi": [], "Kha": [], "Trung binh": []};
score.forEach((name, d) { if (d >= 8) { groups["Gioi"]!.add(name); } else if (d >= 6.5) { groups["Kha"]!.add(name); } else { groups["Trung binh"]!.add(name); } });
print(groups);}Nhóm 7: Hàm (Function)
Phần tiêu đề “Nhóm 7: Hàm (Function)”Xem thêm lý thuyết: Định nghĩa và tạo một hàm, Tham số và Đối số, Giá trị trả về (return).
81. Hàm kiểm tra số nguyên tố
Viết hàm is_prime(n) trả về True/False cho biết n có phải số nguyên tố không.
Xem đáp án
def is_prime(n): if n < 2: return False for i in range(2, int(n ** 0.5) + 1): if n % i == 0: return False return True
print(is_prime(17)) # Trueprint(is_prime(15)) # False#include <iostream>#include <cmath>using namespace std;
bool isPrime(int n) { if (n < 2) return false; for (int i = 2; i <= (int)sqrt(n); i++) { if (n % i == 0) return false; } return true;}
int main() { cout << boolalpha << isPrime(17) << endl; // true cout << boolalpha << isPrime(15) << endl; // false return 0;}public class Main { static boolean isPrime(int n) { if (n < 2) return false; for (int i = 2; i <= Math.sqrt(n); i++) { if (n % i == 0) return false; } return true; }
public static void main(String[] args) { System.out.println(isPrime(17)); // true System.out.println(isPrime(15)); // false }}import kotlin.math.sqrt
fun isPrime(n: Int): Boolean { if (n < 2) return false for (i in 2..sqrt(n.toDouble()).toInt()) { if (n % i == 0) return false } return true}
fun main() { println(isPrime(17)) // true println(isPrime(15)) // false}import 'dart:math';
bool isPrime(int n) { if (n < 2) return false; for (int i = 2; i <= sqrt(n); i++) { if (n % i == 0) return false; } return true;}
void main() { print(isPrime(17)); // true print(isPrime(15)); // false}82. Hàm tính giai thừa
Viết hàm factorial(n) trả về giai thừa của n.
Xem đáp án
def factorial(n): result = 1 for i in range(1, n + 1): result *= i return result
print(factorial(5)) # 120#include <iostream>using namespace std;
long long factorial(int n) { long long result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result;}
int main() { cout << factorial(5) << endl; // 120 return 0;}public class Main { static long factorial(int n) { long result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; }
public static void main(String[] args) { System.out.println(factorial(5)); // 120 }}fun factorial(n: Int): Long { var result = 1L for (i in 1..n) { result *= i } return result}
fun main() { println(factorial(5)) // 120}int factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result;}
void main() { print(factorial(5)); // 120}83. Hàm với tham số mặc định
Viết hàm introduce(name, age=18) in ra câu giới thiệu, nếu không truyền age thì mặc định là 18.
Xem đáp án
def introduce(name, age=18): print(f"Tôi tên là {name}, {age} tuổi.")
introduce("Phúc")introduce("Lan", 20)#include <iostream>using namespace std;
void introduce(string name, int age = 18) { cout << "Toi ten la " << name << ", " << age << " tuoi." << endl;}
int main() { introduce("Phuc"); introduce("Lan", 20); return 0;}public class Main { static void introduce(String name, int age) { System.out.println("Toi ten la " + name + ", " + age + " tuoi."); }
static void introduce(String name) { introduce(name, 18); }
public static void main(String[] args) { introduce("Phuc"); introduce("Lan", 20); }}fun introduce(name: String, age: Int = 18) { println("Toi ten la $name, $age tuoi.")}
fun main() { introduce("Phuc") introduce("Lan", 20)}void introduce(String name, {int age = 18}) { print("Toi ten la $name, $age tuoi.");}
void main() { introduce("Phuc"); introduce("Lan", age: 20);}*84. Hàm với số lượng tham số bất kỳ (args)
*args cho phép một hàm nhận vào số lượng tham số không giới hạn (xem thêm: *args và **kwargs). Viết hàm total(*num) nhận vào số lượng tham số bất kỳ và trả về tổng của chúng.
Xem đáp án
def total(*num): return sum(num)
print(total(1, 2, 3)) # 6print(total(1, 2, 3, 4, 5)) # 15#include <iostream>#include <vector>using namespace std;
// C++ chuẩn không có *args - dùng std::vector hoặc initializer_list làm tương đươngint total(initializer_list<int> nums) { int sum = 0; for (int n : nums) sum += n; return sum;}
int main() { cout << total({1, 2, 3}) << endl; // 6 cout << total({1, 2, 3, 4, 5}) << endl; // 15 return 0;}public class Main { static int total(int... nums) { int sum = 0; for (int n : nums) sum += n; return sum; }
public static void main(String[] args) { System.out.println(total(1, 2, 3)); // 6 System.out.println(total(1, 2, 3, 4, 5)); // 15 }}fun total(vararg nums: Int): Int { return nums.sum()}
fun main() { println(total(1, 2, 3)) // 6 println(total(1, 2, 3, 4, 5)) // 15}int total(List<int> nums) { return nums.reduce((a, b) => a + b);}
void main() { print(total([1, 2, 3])); // 6 print(total([1, 2, 3, 4, 5])); // 15}85. Hàm trả về nhiều giá trị
Viết hàm get_stats(numbers) trả về đồng thời giá trị nhỏ nhất, lớn nhất và trung bình cộng của một list số.
Xem đáp án
def get_stats(numbers): return min(numbers), max(numbers), sum(numbers) / len(numbers)
smallest, largest, average = get_stats([4, 8, 15, 16, 23, 42])print(smallest, largest, average)#include <iostream>#include <vector>#include <tuple>#include <algorithm>using namespace std;
tuple<int, int, double> getStats(vector<int>& numbers) { int smallest = *min_element(numbers.begin(), numbers.end()); int largest = *max_element(numbers.begin(), numbers.end()); double sum = 0; for (int n : numbers) sum += n; double average = sum / numbers.size(); return {smallest, largest, average};}
int main() { vector<int> numbers = {4, 8, 15, 16, 23, 42}; auto [smallest, largest, average] = getStats(numbers); cout << smallest << " " << largest << " " << average << endl; return 0;}public class Main { record Stats(int smallest, int largest, double average) {}
static Stats getStats(int[] numbers) { int smallest = numbers[0], largest = numbers[0], sum = 0; for (int n : numbers) { if (n < smallest) smallest = n; if (n > largest) largest = n; sum += n; } return new Stats(smallest, largest, (double) sum / numbers.length); }
public static void main(String[] args) { int[] numbers = {4, 8, 15, 16, 23, 42}; Stats stats = getStats(numbers); System.out.println(stats.smallest() + " " + stats.largest() + " " + stats.average()); }}data class Stats(val smallest: Int, val largest: Int, val average: Double)
fun getStats(numbers: List<Int>): Stats { return Stats(numbers.min(), numbers.max(), numbers.average())}
fun main() { val (smallest, largest, average) = getStats(listOf(4, 8, 15, 16, 23, 42)) println("$smallest $largest $average")}(int, int, double) getStats(List<int> numbers) { int smallest = numbers.reduce((a, b) => a < b ? a : b); int largest = numbers.reduce((a, b) => a > b ? a : b); double average = numbers.reduce((a, b) => a + b) / numbers.length; return (smallest, largest, average);}
void main() { var (smallest, largest, average) = getStats([4, 8, 15, 16, 23, 42]); print("$smallest $largest $average");}86. Hàm lambda
Lambda là cách viết một hàm ngắn gọn trên 1 dòng, không cần đặt tên bằng def (xem thêm: Lambda Function). Dùng lambda để viết một hàm bình phương một số, và một hàm kiểm tra số chẵn.
Xem đáp án
square = lambda x: x ** 2is_even = lambda x: x % 2 == 0
print(square(5)) # 25print(is_even(4)) # True#include <iostream>using namespace std;
int main() { auto square = [](int x) { return x * x; }; auto isEven = [](int x) { return x % 2 == 0; };
cout << square(5) << endl; // 25 cout << boolalpha << isEven(4) << endl; // true return 0;}import java.util.function.Function;import java.util.function.Predicate;
public class Main { public static void main(String[] args) { Function<Integer, Integer> square = x -> x * x; Predicate<Integer> isEven = x -> x % 2 == 0;
System.out.println(square.apply(5)); // 25 System.out.println(isEven.test(4)); // true }}fun main() { val square = { x: Int -> x * x } val isEven = { x: Int -> x % 2 == 0 }
println(square(5)) // 25 println(isEven(4)) // true}void main() { var square = (int x) => x * x; var isEven = (int x) => x % 2 == 0;
print(square(5)); // 25 print(isEven(4)); // true}87. Dùng map, filter với lambda
filter(hàm, list) giữ lại các phần tử mà hàm trả về True; map(hàm, list) áp dụng hàm lên từng phần tử và trả về kết quả mới. Cho list số [1, 2, 3, 4, 5, 6]. Dùng filter để lấy các số chẵn, dùng map để bình phương từng số chẵn đó.
Xem đáp án
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))square = list(map(lambda x: x ** 2, even_numbers))
print(even_numbers) # [2, 4, 6]print(square) # [4, 16, 36]#include <iostream>#include <vector>#include <algorithm>using namespace std;
int main() { vector<int> numbers = {1, 2, 3, 4, 5, 6};
vector<int> evenNumbers; copy_if(numbers.begin(), numbers.end(), back_inserter(evenNumbers), [](int x) { return x % 2 == 0; });
vector<int> square; transform(evenNumbers.begin(), evenNumbers.end(), back_inserter(square), [](int x) { return x * x; });
for (int x : evenNumbers) cout << x << " "; cout << endl; for (int x : square) cout << x << " "; cout << endl; return 0;}import java.util.List;import java.util.stream.Collectors;
public class Main { public static void main(String[] args) { List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6);
List<Integer> evenNumbers = numbers.stream() .filter(x -> x % 2 == 0) .collect(Collectors.toList());
List<Integer> square = evenNumbers.stream() .map(x -> x * x) .collect(Collectors.toList());
System.out.println(evenNumbers); // [2, 4, 6] System.out.println(square); // [4, 16, 36] }}fun main() { val numbers = listOf(1, 2, 3, 4, 5, 6)
val evenNumbers = numbers.filter { it % 2 == 0 } val square = evenNumbers.map { it * it }
println(evenNumbers) // [2, 4, 6] println(square) // [4, 16, 36]}void main() { List<int> numbers = [1, 2, 3, 4, 5, 6];
List<int> evenNumbers = numbers.where((x) => x % 2 == 0).toList(); List<int> square = evenNumbers.map((x) => x * x).toList();
print(evenNumbers); // [2, 4, 6] print(square); // [4, 16, 36]}88. Hàm chuyển đổi nhiệt độ
Viết 2 hàm c_to_f(c) và f_to_c(f) để chuyển đổi qua lại giữa độ C và độ F.
Xem đáp án
def c_to_f(c): return c * 9 / 5 + 32
def f_to_c(f): return (f - 32) * 5 / 9
print(c_to_f(100)) # 212.0print(f_to_c(32)) # 0.0#include <iostream>using namespace std;
double cToF(double c) { return c * 9 / 5 + 32;}
double fToC(double f) { return (f - 32) * 5 / 9;}
int main() { cout << cToF(100) << endl; // 212 cout << fToC(32) << endl; // 0 return 0;}public class Main { static double cToF(double c) { return c * 9 / 5 + 32; }
static double fToC(double f) { return (f - 32) * 5 / 9; }
public static void main(String[] args) { System.out.println(cToF(100)); // 212.0 System.out.println(fToC(32)); // 0.0 }}fun cToF(c: Double): Double = c * 9 / 5 + 32
fun fToC(f: Double): Double = (f - 32) * 5 / 9
fun main() { println(cToF(100.0)) // 212.0 println(fToC(32.0)) // 0.0}double cToF(double c) { return c * 9 / 5 + 32;}
double fToC(double f) { return (f - 32) * 5 / 9;}
void main() { print(cToF(100)); // 212.0 print(fToC(32)); // 0.0}89. Hàm kiểm tra chuỗi Palindrome
Viết hàm is_palindrome(s) kiểm tra chuỗi s có phải là palindrome không, bỏ qua khoảng trắng và không phân biệt hoa/thường.
Xem đáp án
def is_palindrome(s): s = s.replace(" ", "").lower() return s == s[::-1]
print(is_palindrome("Level")) # Trueprint(is_palindrome("a man a plan a canal panama")) # Trueprint(is_palindrome("hello")) # False#include <iostream>#include <algorithm>#include <cctype>using namespace std;
bool isPalindrome(string s) { string cleaned; for (char c : s) { if (c != ' ') cleaned += tolower(c); } string reversed = cleaned; reverse(reversed.begin(), reversed.end()); return cleaned == reversed;}
int main() { cout << boolalpha << isPalindrome("Level") << endl; // true cout << boolalpha << isPalindrome("a man a plan a canal panama") << endl; // true cout << boolalpha << isPalindrome("hello") << endl; // false return 0;}public class Main { static boolean isPalindrome(String s) { String cleaned = s.replace(" ", "").toLowerCase(); String reversed = new StringBuilder(cleaned).reverse().toString(); return cleaned.equals(reversed); }
public static void main(String[] args) { System.out.println(isPalindrome("Level")); // true System.out.println(isPalindrome("a man a plan a canal panama")); // true System.out.println(isPalindrome("hello")); // false }}fun isPalindrome(s: String): Boolean { val cleaned = s.replace(" ", "").lowercase() return cleaned == cleaned.reversed()}
fun main() { println(isPalindrome("Level")) // true println(isPalindrome("a man a plan a canal panama")) // true println(isPalindrome("hello")) // false}bool isPalindrome(String s) { String cleaned = s.replaceAll(" ", "").toLowerCase(); String reversed = String.fromCharCodes(cleaned.runes.toList().reversed); return cleaned == reversed;}
void main() { print(isPalindrome("Level")); // true print(isPalindrome("a man a plan a canal panama")); // true print(isPalindrome("hello")); // false}90. Hàm đệ quy tính giai thừa
Viết hàm factorial(n) tính giai thừa bằng đệ quy (hàm tự gọi lại chính nó).
Xem đáp án
def factorial(n): if n <= 1: return 1 return n * factorial(n - 1)
print(factorial(5)) # 120#include <iostream>using namespace std;
long long factorial(int n) { if (n <= 1) return 1; return n * factorial(n - 1);}
int main() { cout << factorial(5) << endl; // 120 return 0;}public class Main { static long factorial(int n) { if (n <= 1) return 1; return n * factorial(n - 1); }
public static void main(String[] args) { System.out.println(factorial(5)); // 120 }}fun factorial(n: Int): Long { if (n <= 1) return 1 return n * factorial(n - 1)}
fun main() { println(factorial(5)) // 120}int factorial(int n) { if (n <= 1) return 1; return n * factorial(n - 1);}
void main() { print(factorial(5)); // 120}Nhóm 8: Đệ quy (Recursion)
Phần tiêu đề “Nhóm 8: Đệ quy (Recursion)”Đệ quy là kỹ thuật một hàm tự gọi lại chính nó để giải quyết bài toán nhỏ hơn, cho đến khi gặp điều kiện dừng (base case). Xem thêm lý thuyết: Đệ quy (Recursion).
91. Đệ quy tính tổng 1 đến n
Viết hàm đệ quy tong(n) tính tổng các số từ 1 đến n.
Xem đáp án
def total(n): if n == 0: return 0 return n + total(n - 1)
print(total(10)) # 55#include <iostream>using namespace std;
int total(int n) { if (n == 0) return 0; return n + total(n - 1);}
int main() { cout << total(10) << endl; // 55 return 0;}public class Main { static int total(int n) { if (n == 0) return 0; return n + total(n - 1); }
public static void main(String[] args) { System.out.println(total(10)); // 55 }}fun total(n: Int): Int { if (n == 0) return 0 return n + total(n - 1)}
fun main() { println(total(10)) // 55}int total(int n) { if (n == 0) return 0; return n + total(n - 1);}
void main() { print(total(10)); // 55}92. Đệ quy tính số Fibonacci thứ n
Viết hàm đệ quy fib(n) trả về số Fibonacci thứ n (bắt đầu từ fib(0) = 0, fib(1) = 1).
Xem đáp án
def fib(n): if n <= 1: return n return fib(n - 1) + fib(n - 2)
print(fib(10)) # 55#include <iostream>using namespace std;
int fib(int n) { if (n <= 1) return n; return fib(n - 1) + fib(n - 2);}
int main() { cout << fib(10) << endl; // 55 return 0;}public class Main { static int fib(int n) { if (n <= 1) return n; return fib(n - 1) + fib(n - 2); }
public static void main(String[] args) { System.out.println(fib(10)); // 55 }}fun fib(n: Int): Int { if (n <= 1) return n return fib(n - 1) + fib(n - 2)}
fun main() { println(fib(10)) // 55}int fib(int n) { if (n <= 1) return n; return fib(n - 1) + fib(n - 2);}
void main() { print(fib(10)); // 55}93. Đệ quy đảo ngược chuỗi
Viết hàm đệ quy reverse(s) trả về chuỗi s bị đảo ngược, không dùng s[::-1].
Xem đáp án
def reverse(s): if len(s) <= 1: return s return reverse(s[1:]) + s[0]
print(reverse("python")) # nohtyp#include <iostream>using namespace std;
string reverse(string s) { if (s.length() <= 1) return s; return reverse(s.substr(1)) + s[0];}
int main() { cout << reverse("python") << endl; // nohtyp return 0;}public class Main { static String reverse(String s) { if (s.length() <= 1) return s; return reverse(s.substring(1)) + s.charAt(0); }
public static void main(String[] args) { System.out.println(reverse("python")); // nohtyp }}fun reverse(s: String): String { if (s.length <= 1) return s return reverse(s.substring(1)) + s[0]}
fun main() { println(reverse("python")) // nohtyp}String reverse(String s) { if (s.length <= 1) return s; return reverse(s.substring(1)) + s[0];}
void main() { print(reverse("python")); // nohtyp}94. Đệ quy tính ƯCLN
Viết hàm đệ quy gcd(a, b) tính ước chung lớn nhất của a và b.
Xem đáp án
def gcd(a, b): if b == 0: return a return gcd(b, a % b)
print(gcd(48, 18)) # 6#include <iostream>using namespace std;
int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b);}
int main() { cout << gcd(48, 18) << endl; // 6 return 0;}public class Main { static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); }
public static void main(String[] args) { System.out.println(gcd(48, 18)); // 6 }}fun gcd(a: Int, b: Int): Int { if (b == 0) return a return gcd(b, a % b)}
fun main() { println(gcd(48, 18)) // 6}int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b);}
void main() { print(gcd(48, 18)); // 6}95. Đệ quy đếm số chữ số
Viết hàm đệ quy count_digits(n) đếm số lượng chữ số của số nguyên dương n.
Xem đáp án
def count_digits(n): if n < 10: return 1 return 1 + count_digits(n // 10)
print(count_digits(123456)) # 6#include <iostream>using namespace std;
int countDigits(int n) { if (n < 10) return 1; return 1 + countDigits(n / 10);}
int main() { cout << countDigits(123456) << endl; // 6 return 0;}public class Main { static int countDigits(int n) { if (n < 10) return 1; return 1 + countDigits(n / 10); }
public static void main(String[] args) { System.out.println(countDigits(123456)); // 6 }}fun countDigits(n: Int): Int { if (n < 10) return 1 return 1 + countDigits(n / 10)}
fun main() { println(countDigits(123456)) // 6}int countDigits(int n) { if (n < 10) return 1; return 1 + countDigits(n ~/ 10);}
void main() { print(countDigits(123456)); // 6}Nhóm 9: File và Exception Handling
Phần tiêu đề “Nhóm 9: File và Exception Handling”Xem thêm lý thuyết: Đọc và Ghi File, Exception Handling (Try/Except).
96. Ghi và đọc file văn bản
Ghi danh sách 3 câu vào file data.txt (mỗi câu 1 dòng), sau đó đọc lại và in ra từng dòng.
Xem đáp án
lines = ["Xin chao", "Toi hoc Python", "Rat vui!"]
with open("data.txt", "w", encoding="utf-8") as f: for line in lines: f.write(line + "\n")
with open("data.txt", "r", encoding="utf-8") as f: for line in f: print(line.strip())#include <iostream>#include <fstream>#include <vector>#include <string>using namespace std;
int main() { vector<string> lines = {"Xin chao", "Toi hoc Cpp", "Rat vui!"};
ofstream fout("data.txt"); for (auto& line : lines) fout << line << "\n"; fout.close();
ifstream fin("data.txt"); string line; while (getline(fin, line)) cout << line << endl;
return 0;}import java.io.*;import java.util.*;
public class Main { public static void main(String[] args) throws IOException { List<String> lines = Arrays.asList("Xin chao", "Toi hoc Java", "Rat vui!");
try (PrintWriter fout = new PrintWriter(new FileWriter("data.txt"))) { for (String line : lines) fout.println(line); }
try (BufferedReader fin = new BufferedReader(new FileReader("data.txt"))) { String line; while ((line = fin.readLine()) != null) System.out.println(line); } }}import java.io.File
fun main() { val lines = listOf("Xin chao", "Toi hoc Kotlin", "Rat vui!")
File("data.txt").writeText(lines.joinToString("\n") + "\n")
File("data.txt").forEachLine { println(it) }}import 'dart:io';
void main() { final lines = ["Xin chao", "Toi hoc Dart", "Rat vui!"];
final file = File("data.txt"); file.writeAsStringSync(lines.join("\n") + "\n");
final content = file.readAsLinesSync(); for (var line in content) { print(line); }}97. Đếm số dòng, số từ trong file
Cho một file văn bản, đếm số dòng và tổng số từ có trong file đó.
Xem đáp án
with open("data.txt", "r", encoding="utf-8") as f: lines = f.readlines()
line_count = len(lines)word_count = sum(len(line.split()) for line in lines)
print("Số dòng:", line_count)print("Số từ:", word_count)#include <iostream>#include <fstream>#include <sstream>using namespace std;
int main() { ifstream fin("data.txt"); string line; int lineCount = 0, wordCount = 0;
while (getline(fin, line)) { lineCount++; istringstream iss(line); string word; while (iss >> word) wordCount++; }
cout << "So dong: " << lineCount << endl; cout << "So tu: " << wordCount << endl; return 0;}import java.io.*;import java.util.*;
public class Main { public static void main(String[] args) throws IOException { int lineCount = 0, wordCount = 0;
try (BufferedReader fin = new BufferedReader(new FileReader("data.txt"))) { String line; while ((line = fin.readLine()) != null) { lineCount++; wordCount += line.trim().isEmpty() ? 0 : line.trim().split("\\s+").length; } }
System.out.println("So dong: " + lineCount); System.out.println("So tu: " + wordCount); }}import java.io.File
fun main() { val lines = File("data.txt").readLines() val lineCount = lines.size val wordCount = lines.sumOf { it.trim().split(Regex("\\s+")).count { w -> w.isNotEmpty() } }
println("So dong: $lineCount") println("So tu: $wordCount")}import 'dart:io';
void main() { final lines = File("data.txt").readAsLinesSync(); final lineCount = lines.length; final wordCount = lines.fold<int>( 0, (sum, line) => sum + line.trim().split(RegExp(r'\s+')).where((w) => w.isNotEmpty).length);
print("So dong: $lineCount"); print("So tu: $wordCount");}98. Xử lý lỗi chia cho 0
Viết chương trình đọc vào 2 số và chia chúng cho nhau, dùng try/except để xử lý trường hợp chia cho 0.
Xem đáp án
while True: try: a = float(input("a: ")) b = float(input("b: ")) break except ValueError: print("Vui lòng nhập số hợp lệ, hãy nhập lại!")
try: print(a / b)except ZeroDivisionError: print("Lỗi: không thể chia cho 0")#include <iostream>using namespace std;
int main() { double a, b; cout << "a: "; cin >> a; cout << "b: "; cin >> b;
try { if (b == 0) throw runtime_error("khong the chia cho 0"); cout << a / b << endl; } catch (const runtime_error& e) { cout << "Loi: " << e.what() << endl; } return 0;}import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("a: "); double a = sc.nextDouble(); System.out.print("b: "); double b = sc.nextDouble();
try { if (b == 0) throw new ArithmeticException("khong the chia cho 0"); System.out.println(a / b); } catch (ArithmeticException e) { System.out.println("Loi: " + e.getMessage()); } }}fun main() { print("a: ") val a = readLine()!!.toDouble() print("b: ") val b = readLine()!!.toDouble()
try { if (b == 0.0) throw ArithmeticException("khong the chia cho 0") println(a / b) } catch (e: ArithmeticException) { println("Loi: ${e.message}") }}import 'dart:io';
void main() { stdout.write("a: "); final a = double.parse(stdin.readLineSync()!); stdout.write("b: "); final b = double.parse(stdin.readLineSync()!);
try { if (b == 0) throw Exception("khong the chia cho 0"); print(a / b); } catch (e) { print("Loi: $e"); }}99. Xử lý lỗi nhập liệu sai định dạng
Viết chương trình yêu cầu người dùng nhập một số nguyên, dùng try/except để bắt lỗi nếu người dùng nhập chữ thay vì số.
Xem đáp án
while True: try: n = int(input("Nhập một số nguyên: ")) break except ValueError: print("Lỗi: giá trị nhập vào không phải là số nguyên, hãy nhập lại!")
print("Bạn đã nhập:", n)#include <iostream>#include <sstream>using namespace std;
int main() { int n; string input;
while (true) { cout << "Nhap mot so nguyen: "; cin >> input; istringstream iss(input); if (iss >> n && iss.eof()) break; cout << "Loi: gia tri nhap vao khong phai la so nguyen, hay nhap lai!" << endl; }
cout << "Ban da nhap: " << n << endl; return 0;}import java.util.Scanner;import java.util.InputMismatchException;
public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = 0;
while (true) { System.out.print("Nhap mot so nguyen: "); try { n = Integer.parseInt(sc.nextLine().trim()); break; } catch (NumberFormatException e) { System.out.println("Loi: gia tri nhap vao khong phai la so nguyen, hay nhap lai!"); } }
System.out.println("Ban da nhap: " + n); }}fun main() { var n: Int while (true) { print("Nhap mot so nguyen: ") val input = readLine()!!.trim() val parsed = input.toIntOrNull() if (parsed != null) { n = parsed break } println("Loi: gia tri nhap vao khong phai la so nguyen, hay nhap lai!") }
println("Ban da nhap: $n")}import 'dart:io';
void main() { int? n; while (n == null) { stdout.write("Nhap mot so nguyen: "); n = int.tryParse(stdin.readLineSync()!.trim()); if (n == null) { print("Loi: gia tri nhap vao khong phai la so nguyen, hay nhap lai!"); } }
print("Ban da nhap: $n");}100. Tự định nghĩa Exception
Viết một class exception tùy chỉnh NegativeNumberError. Viết hàm check_positive(n) ném ra exception này nếu n âm.
Xem đáp án
class NegativeNumberError(Exception): pass
def check_positive(n): if n < 0: raise NegativeNumberError(f"{n} là số âm, không hợp lệ") return n
try: check_positive(-5)except NegativeNumberError as e: print("Bắt được lỗi:", e)#include <iostream>#include <stdexcept>#include <string>using namespace std;
class NegativeNumberError : public runtime_error {public: NegativeNumberError(const string& msg) : runtime_error(msg) {}};
int checkPositive(int n) { if (n < 0) throw NegativeNumberError(to_string(n) + " la so am, khong hop le"); return n;}
int main() { try { checkPositive(-5); } catch (const NegativeNumberError& e) { cout << "Bat duoc loi: " << e.what() << endl; } return 0;}public class Main { static class NegativeNumberError extends RuntimeException { NegativeNumberError(String msg) { super(msg); } }
static int checkPositive(int n) { if (n < 0) throw new NegativeNumberError(n + " la so am, khong hop le"); return n; }
public static void main(String[] args) { try { checkPositive(-5); } catch (NegativeNumberError e) { System.out.println("Bat duoc loi: " + e.getMessage()); } }}class NegativeNumberError(message: String) : Exception(message)
fun checkPositive(n: Int): Int { if (n < 0) throw NegativeNumberError("$n la so am, khong hop le") return n}
fun main() { try { checkPositive(-5) } catch (e: NegativeNumberError) { println("Bat duoc loi: ${e.message}") }}class NegativeNumberError implements Exception { final String message; NegativeNumberError(this.message);
@override String toString() => message;}
int checkPositive(int n) { if (n < 0) throw NegativeNumberError("$n la so am, khong hop le"); return n;}
void main() { try { checkPositive(-5); } catch (e) { print("Bat duoc loi: $e"); }}Làm xong 100 bài này rồi? Tiếp tục với các bài khó hơn ở trang Bài tập lập trình - Nâng cao.