Computing GCD
Write a function to return greatest common dividers (GCDs) of 5 pairs of positive integer numbers.HINT
The GCD of two positive integers x and y equals the GCD of x-y and y if x>y.
Alternatively, you can iterate through all numbers from min(x,y) to 1 to find a GCD.
百度百科:
更相減損法
#include <iostream>
using namespace std;
//Let max(x,y)=max(x,y) - min(x,y),until x == y;
//At last,gcd of x and y is just x ( or y ) , when x == y;
void gcd(int x, int y) {
while (x != y) {
if (x > y) {
x = x - y;
}
else {
y = y - x;
}
}
cout << x << endl;
}
int main() {
for (int i = 1; i <= 5; ++ i) {
int a, b;
cin >> a >> b;
gcd (a, b);
}
}
Emirp
An emirp (prime spelled backwards) is a prime number whose reversal is also a prime. For example, 17 is a prime and 71 is also a prime. So 17 and 71 are emirps. Given a positive number n, write a program that displays the first n emirps. Display 10 numbers per line.#include <iostream>
#include <cmath>
using namespace std;
// To check a integer is a prime number or not;
bool isPrime(int x) {
if (x == 2) {
return 1;
goto Break;
}
for (int i = 2; i <= sqrt (x); ++ i) {
if (x % i == 0) {
return 0;
goto Break;
}
}
return 1;
Break: ;
}
// To get a reversal of a integer;
int rev(int x) {
int rev1 = 0;
while(x) {
rev1 *= 10;
rev1 += (x % 10);
x /= 10;;
}
return rev1;
}
int main() {
int n;
cin >> n;
for (int i = 2, num1 = 0; num1 < n; ++ i) {
if (isPrime (i) && isPrime (rev (i))) {
cout << i << ' ';
num1 += 1;
if (num1 % 10 == 0){
cout << endl;
}
}
}
}