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.
百度百科:
更相减损法
《九章算术》是中国古代的数学专著,其中的“更相减损术”可以用来求两个数的最大公约数,即“可半者半之,不可半者,副置分母、子之数,以少减多,更相减损,求其等也。以等数约之。”
翻译成现代语言如下:
第一步:任意给定两个正整数;判断它们是否都是偶数。若是,则用2约简;若不是则执行第二步。
第二步:以较大的数减较小的数,接着把所得的差与较小的数比较,并以大数减小数。继续这个操作,直到所得的减数和差相等为止。
则第一步中约掉的若干个2与第二步中等数的乘积就是所求的最大公约数。
其中所说的“等数”,就是最大公约数。求“等数”的办法是“更相减损”法。所以更相减损法也叫 等值算法。
#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;
}
}
}
}版权声明:本文为duolabaobao原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。