C++作業5.|最大公因數/反素數

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;
			}
		}
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章