Learning C++ Through Problem 1151: What Counts as a Tongtong Number?

Published:

Lao He has recently been learning C++, and the process has been surprisingly enjoyable. After picking up some of the basics, he found that he could already handle a few simple problems, which made the whole thing feel quite rewarding.

Problem description

For this problem, the task can be approached in a very direct way.

Basic idea

The logic is built around factorization and prime checking:

  1. Break the given number into its factors.
  2. Check one by one whether those factors are prime numbers.
  3. Based on the result, output the corresponding message.

Key points involved

Several basic C++ ideas are used together here:

  1. If a number is not prime, then it must have at least one factor no greater than its square root.
  2. Defining functions and calling one function from inside another.
  3. Using the bool type to represent true/false conditions.
  4. Combining multiple small pieces of knowledge to solve a complete problem.

How the code works

The program defines two functions.

  • isPrime(long long x) checks whether a number is prime.
  • yinshu(long long n) loops through the factors of n and tests whether every relevant factor pair consists of prime numbers.

In the prime-checking function, once a divisor is found, the result can immediately be marked as false and the loop can stop. There is no need to keep checking after that.

In the factor-traversal function, the loop only needs to go up to the square root of n, written here in the form i * i <= n. If i divides n, then the code checks both i and n / i. If both are prime, it continues; otherwise, it determines that the number does not meet the requirement.

Code

<pre class="io-enlighter-pre">```
#include <iostream>
#include <cmath>
using namespace std; //定义函数判断是否质数,如果是返回true

int isPrime(long long x) {
    long long i; bool isPrime = true; //平方根的第一种表示方法
    for (int i = 2; i <= sqrt(x); i++) {
    if (x % i == 0) {
    isPrime = false;
    break; // 一旦找到一个因子,就可以确定不是质数 }
    }
return isPrime;
} //定义函数遍历每一个因数,如果全是是质数返回true

int yinshu(long long n) {
    long long i; //假设因子是质数,如果假设因子是非因数也可。
    bool prime = true; //平方根的第二种表示方法
    for(i = 2; i * i <= n; i++) {
        if(n % i == 0) {
            if (isPrime(i) and isPrime(n / i)) {
            continue;
            } else {
            prime = false; break;
            }
        }
    }
    return prime;
}

int main() {
    long long n;
    cin >> n;
    if(yinshu(n)) {
    cout << It's a Tongtong number. << endl;
    } else {
    cout << It's not a Tongtong number. << endl; }
    return 0;
    }

This is a fairly typical beginner-friendly exercise: the idea is not complicated, but it brings together factorization, primality testing, loops, function calls, and boolean logic in one small program. For someone just getting into C++, it is exactly the kind of problem that helps turn scattered syntax into something practical.