目录
A prime number is a positive integer greater than 1 that has no positive integer divisors other than 1 and itself. The smallest prime numbers are 2, 3, 5, 7, 11, and so on. Prime numbers are important in mathematics and computer science because they are used in various algorithms and encryption techniques.
判断一个数是否为素数
#include <iostream>
#include<math.h>
using namespace std;
bool isPrime(int n) {
if (n <= 1)
return false;
for (int i = 2; i <= sqrt(n); i++) {
if (n % i == 0)
return false;
}
return true;
}
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
if (isPrime(num))
cout << num << " is a prime number." << endl;
else
cout << num << " is not a prime number." << endl;
system("pause");
return 0;
}
指定范围内素数个数
#include <iostream>
#include<math.h>
using namespace std;
bool isPrime(int n) {
if (n <= 1)
return false;
for (int i = 2; i <= sqrt(n); i++) {
if (n % i == 0)
return false;
}
return true;
}
int countPrimes(int start, int end) {
int count = 0;
for (int i = start; i <= end; i++) {
if (isPrime(i))
count++;
}
return count;
}
int main() {
int start, end;
cout << "Enter the starting number: ";
cin >> start;
cout << "Enter the ending number: ";
cin >> end;
int count = countPrimes(start, end);
cout << "The number of prime numbers between " << start << " and " << end << " is: " << count << endl;
system("pause");
return 0;
}
完美数
A perfect number is a positive integer that is equal to the sum of its proper positive divisors, excluding the number itself. For example, 6 is a perfect number because its proper positive divisors are 1, 2, and 3, and their sum is equal to 6.
判断一个数是不是完美数:
#include <iostream>
using namespace std;
int getDivisorsSum(int n) {
int sum = 0;
for (int i = 1; i <= n / 2; i++) {
if (n % i == 0) {
sum += i;
}
}
return sum;
}
bool isPerfect(int n) {
return n == getDivisorsSum(n);
}
int main() {
int n;
cout << "Enter a positive integer: ";
cin >> n;
if (isPerfect(n)) {
cout << n << " is a perfect number." << endl;
} else {
cout << n << " is not a perfect number." << endl;
}
system("pause");
return 0;
}
亲和数
An amicable number is a pair of two different numbers so related that the sum of the proper divisors of each is equal to the other number. For example, the smallest pair of amicable numbers is (220, 284).
判断一对数是否为亲和数:
#include <iostream>
#include<math.h>
using namespace std;
int getDivisorsSum(int n) {
int sum = 1;
for (int i = 2; i <= sqrt(n); i++) {
if (n % i == 0) {
if (i == (n / i))
sum = sum + i;
else
sum = sum + (i + n / i);
}
}
return sum;
}
bool isAmicable(int num1, int num2) {
return (getDivisorsSum(num1) == num2 && getDivisorsSum(num2) == num1);
}
int main() {
int num1, num2;
cout << "Enter two different positive integers: ";
cin >> num1 >> num2;
if (isAmicable(num1, num2)) {
cout << num1 << " and " << num2 << " are amicable numbers." << endl;
} else {
cout << num1 << " and " << num2 << " are not amicable numbers." << endl;
}
system("pause");
return 0;
}