Complete code implementation for finding the range of lucky prime numbers

Table of contents

topic

Python code implementation

C code implementation

 C++ code implementation



 

topic


 

A prime number, also known as a prime number, refers to a positive integer that has no other divisors except 1 and itself. For example, 2,3,5,13 are all prime numbers, but 4,9,12,18 are not.

In particular, it is stipulated that 1 is not a prime number (so the prime factorization of natural numbers is unique).

If a number itself is a prime number, and the number obtained after deleting the lowest bit is still a prime number, and then the number obtained after deleting the lowest bit is still a prime number...and so on until we get a one-digit prime number, we call it It is a "lucky prime number".

Therefore, 233 is a "lucky" prime number but 211 is not a lucky prime number: Although 211 is a prime number, 21 is not a prime number. Please program to find all lucky numbers within a certain range.

Input format: Enter two positive integers mn separated by spaces in one line, indicating the range of lucky prime numbers we want to find. Output format: Output all lucky prime numbers in m, m+1, m+2··, n from small to large, each line is output one.

Python code implementation


# 定义一个函数,用于判断一个数是否为素数
def is_prime(num):
    if num < 2:
        return False
    # 遍历2到sqrt(num)之间的数,如果能整除则不是素数
    for i in range(2, int(num**0.5) + 1):
        if num % i == 0:
            return False
    return True

# 定义一个函数,用于找出某个范围内的所有“幸运素数”
def lucky_primes_in_range(m, n):
    lucky_primes = []  # 存储幸运素数的列表
    # 遍历范围内的每个数
    for num in range(m, n + 1):
        if is_prime(num):  # 如果当前数是素数
            str_num = str(num)
            is_lucky = True  # 假设是“幸运素数”
            # 不断去掉最低位,检查剩余部分是否还是素数
            while len(str_num) > 1:
                str_num = str_num[:-1]
                if not is_prime(int(str_num)):
                    is_lucky = False  # 如果不是素数,则不是“幸运素数”
                    break
            if is_lucky:  # 如果是“幸运素数”,添加到结果列表中
                lucky_primes.append(num)
    return lucky_primes  # 返回结果列表

# 输入范围
m, n = map(int, input().split())

# 调用函数,得到结果
result = lucky_primes_in_range(m, n)

# 输出结果
for num in result:
    print(num)

str_num[:-1] is the usage of slice in Python, which means to intercept all characters of the string `str_num`, but not including the last character. Specifically, `[:-1]` means from the beginning of the string to the second to last character.

for example:


str_num = "12345"
result = str_num[:-1]
print(result)

The output is:

1234

In the above code, `str_num[:-1]` takes the beginning of the string `str_num` to the second-to-last character (excluding the second-to-last character), so the result is "1234". This is used in the algorithm in the question to remove the lowest digit of a number.

C code implementation


Certainly! Here's the equivalent program in C:

#include <stdio.h>
#include <stdbool.h>
#include <math.h>

// 函数声明,用于判断一个数是否为素数
bool is_prime(int num);

// 函数声明,用于找出某个范围内的所有“幸运素数”
void lucky_primes_in_range(int m, int n);

int main() {
    // 输入范围
    int m, n;
    scanf("%d %d", &m, &n);

    // 调用函数,得到结果
    lucky_primes_in_range(m, n);

    return 0;
}

// 函数定义,判断一个数是否为素数
bool is_prime(int num) {
    if (num < 2) {
        return false;
    }
    // 遍历2到sqrt(num)之间的数,如果能整除则不是素数
    for (int i = 2; i <= sqrt(num); ++i) {
        if (num % i == 0) {
            return false;
        }
    }
    return true;
}

// 函数定义,找出某个范围内的所有“幸运素数”
void lucky_primes_in_range(int m, int n) {
    // 遍历范围内的每个数
    for (int num = m; num <= n; ++num) {
        // 如果当前数是素数
        if (is_prime(num)) {
            int temp = num;
            bool is_lucky = true;  // 假设是“幸运素数”
            // 不断去掉最低位,检查剩余部分是否还是素数
            while (temp > 9) {
                temp /= 10;
                if (!is_prime(temp)) {
                    is_lucky = false;  // 如果不是素数,则不是“幸运素数”
                    break;
                }
            }
            if (is_lucky) {  // 如果是“幸运素数”,输出到结果
                printf("%d\n", num);
            }
        }
    }
}

In C language, the `bool` type is not natively supported, but after the C99 standard, the `_Bool` type was introduced and the header file `stdbool.h` was provided, which defined `bool` and `true` , `false` and other keywords for ease of use.

Here is a brief introduction to the use of `bool`:

1. Introduce the header file: use the `stdbool.h` header file.

#include <stdbool.h>

2. Define the `bool` type: Use the `_Bool` type to define the `bool` type, and use `true` and `false` to define true and false values.

_Bool myBool = true;  // 声明并初始化为 true

    Or more directly:
 

bool myBool = true;  // C99标准以后支持这种方式

3. Use `bool` type: Use `bool` type for conditional judgment.
 

bool isTrue = true;
bool isFalse = false;
if (isTrue) {
    // 执行条件为真的代码
 } else if (isFalse) {
    // 执行条件为假的代码
}

4. Return `bool` value: The function can return `bool` value.

bool isEven(int number) {
    return number % 2 == 0;
    }

This makes it easier for functions to express the meaning of Boolean values.

Generally speaking, although the C language does not have a native `bool` type, by introducing the `stdbool.h` header file, we can use the `bool`, `true`, and `false` keywords in the C code, making the code more Clear and easy to read.

This C language code implements the function of finding all "lucky prime numbers" within a certain range, similar to the Python version.

 C++ code implementation


The following is the code to implement the above problem in C++, with detailed comments:
 

#include <iostream>
#include <vector>

// 函数判断一个数是否为素数
bool isPrime(int num) {
    if (num < 2) {
        return false;
    }
    for (int i = 2; i * i <= num; ++i) {
        if (num % i == 0) {
            return false;
        }
    }
    return true;
}

// 函数判断一个数是否为幸运素数
bool isLuckyPrime(int num) {
    std::string strNum = std::to_string(num);
    while (strNum.size() > 1) {
        strNum.pop_back();
        if (!isPrime(std::stoi(strNum))) {
            return false;
        }
    }
    return true;
}

// 函数找出指定范围内的所有幸运素数
std::vector<int> luckyPrimesInRange(int m, int n) {
    std::vector<int> luckyPrimes;
    for (int num = m; num <= n; ++num) {
        if (isPrime(num) && isLuckyPrime(num)) {
            luckyPrimes.push_back(num);
        }
    }
    return luckyPrimes;
}

int main() {
    // 输入范围
    int m, n;
    std::cout << "Enter the range (m n): ";
    std::cin >> m >> n;

    // 获取结果
    std::vector<int> result = luckyPrimesInRange(m, n);

    // 输出结果
    std::cout << "Lucky Primes in the range " << m << " to " << n << " are:\n";
    for (int num : result) {
        std::cout << num << '\n';
    }

    return 0;
}

This C++ code contains two judgment functions `isPrime` and `isLuckyPrime`, and the main function `luckyPrimesInRange` is used to find all lucky prime numbers in the specified range. In the `main` function, the user inputs the range and then prints the result.

This code defines a function named `luckyPrimesInRange`,The purpose of this function is to find all lucky prime numbers in the specified range and store them in an integer in vector (`std::vector<int>`). Here's a detailed explanation of the function:


std::vector<int> luckyPrimesInRange(int m, int n) {
    // 创建一个整数向量,用于存储找到的幸运素数
    std::vector<int> luckyPrimes;

    // 遍历指定范围内的每个数
    for (int num = m; num <= n; ++num) {
        // 判断当前数是否为素数且是幸运素数
        if (isPrime(num) && isLuckyPrime(num)) {
            // 如果是,则将该数添加到 luckyPrimes 向量中
            luckyPrimes.push_back(num);
        }
    }

    // 返回包含所有幸运素数的向量
    return luckyPrimes;
}

The steps of the function are as follows:

1. Create vector: Create an integer vector named `luckyPrimes` to store the found lucky primes.

2. Traverse the range:Use `for` to loop through each number from `m` to `n`.

3. Determine prime numbers and lucky prime numbers:For each number, determine whether it is a prime number by calling the `isPrime` function, and then determine whether it is lucky by calling the `isLuckyPrime` function Prime number.

4. Add to vector:If the current number is a prime number and it is a lucky prime, add itto the `luckyPrimes` vector.

5. Return result:Finally, the vector containing all lucky prime numbers is returned to the caller.

The main purpose of this function is to provide a convenient interface to obtain all lucky prime numbers found within a specified range.


In this C++ code, `std::vector<int>` is a dynamic array used to store integers. The purpose of the vector here is to hold all the lucky primes found so that they can be returned to the caller later. Here are some key uses of vectors:

1. Dynamic size:A vector is an array of dynamically allocated memory that can dynamically grow or shrink in size as needed. This makes them very flexible and able to accommodate an indeterminate number of elements.

2. Simplified memory management:Vectors handle the complexity of memory management. It automatically handles memory allocation and deallocation, eliminating the need for programmers to manually manage memory.

3. Random access: Vectors allow fast random access through indexing. In this example, the elements in the vector can be accessed by index, e.g. `luckyPrimes[0]` represents the first lucky prime found.

4. Provides rich methods:The vector class provides various useful methods, such as `push_back` (adding elements to the end of the vector), `size` (getting the contents of the vector number of elements), etc. These methods simplify operations on vectors.

5. As a function return value:A vector is a convenient function return type because it can hold a varying number of elements and can be easily passed to the caller.

In this particular code, the purpose of the vector is to collect and return all lucky primes found within a given range, making the code more modular and readable.

Guess you like

Origin blog.csdn.net/qq_50942093/article/details/134620374