用c++写出从2到n的所有半素数和素数
时间: 2024-09-30 13:12:29 浏览: 51
在 C++ 中,我们可以创建一个函数来找出从2到n之间的所有半素数(也称作阿姆斯特朗数)和素数。首先,我们分别定义两个辅助函数来检查一个数字是否是半素数和素数。
**注意:** 半素数是指其各位数字的立方和等于该数本身的数,例如 153 = 1^3 + 5^3 + 3^3。
```cpp
#include <iostream>
#include <vector>
bool isArmstrongNumber(int num) {
int sumOfCubes = 0;
int temp = num;
while (temp > 0) {
int digit = temp % 10;
sumOfCubes += std::pow(digit, 3);
temp /= 10;
}
return sumOfCubes == num;
}
bool isPrime(int num) {
if (num <= 1)
return false;
for (int i = 2; i * i <= num; ++i) {
if (num % i == 0)
return false;
}
return true;
}
void printNumbersFromTo(int start, int end) {
std::vector<int> halfPrimes, primes;
for (int i = start; i <= end; ++i) {
if (isArmstrongNumber(i))
halfPrimes.push_back(i);
if (isPrime(i))
primes.push_back(i);
}
std::cout << "Half-Squares from " << start << " to " << end << " are: ";
for (const auto& num : halfPrimes)
std::cout << num << " ";
std::cout << "\nPrimes from " << start << " to " << end << " are: ";
for (const auto& num : primes)
std::cout << num << " ";
}
int main() {
int n;
std::cout << "Enter a number n: ";
std::cin >> n;
printNumbersFromTo(2, n);
return 0;
}
```
阅读全文