C++ 14的<algorithm>有內建一個__gcd的函數,不過實在很不顯眼。
(註:是兩個底線)
# include <iostream>
# include <algorithm>
int main(){
int G,N,i,j;
while(std::cin>>N && N != 0){
G = 0;
for(i = 1 ; i<N ; i++)
for(j = i+1 ; j<=N ; j++)
G += __gcd(i,j);
std::cout << G << '\n';
}
}
以下提供幾個以輾轉相除法(Euclidean algorithm)實作GCD的方式作為參考。
int gcd(int a,int b){
if(b == 0)
return a;
return gcd(b, a%b);
}
int gcd(int a,int b){
int c;
while(b != 0){
c = a%b;
a = b;
b = c;
}
return a;
}
int gcd(int a, int b){
if (b != 0)
while(a %= b && b %= a);
return a+b;
}
C. 完美平方數 #include <iostream> #include <math.h> using namespace std; int numSquares(int n); int main() { int num, ans;
Jan 27, 2022E. 鐵路 本題源自於Onling Judge:514 - Rails 題目目標在於給定出站順序的前提下,利用已知入站順序1~N, 確定是否仍能夠以目標出站順序離開。 有一個簡單的想法,我們利用queue的特性來維護出站順序、 利用stack的特性來維護入站順序, 並依次比較它們的front/top是否相同,如果相同就安排出站(pop)。
Jan 27, 2022C. 組合 #include<bits/stdc++.h> using namespace std; vector<int> a; bool first=true,f=true; fstream input,output; void find(int g,vector<int> &can,int p){ if(!g){ if(!first){
Sep 19, 2021D. Flood Fill # include <bits/stdc++.h> using namespace std; int m[102][102]; struct Fill{ int x,y,t; };
Sep 16, 2021or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up