網易2017春招筆試——集合
阿新 • • 發佈:2019-01-07
集合
題目
小易最近在數學課上學習到了集合的概念,集合有三個特徵:1.確定性 2.互異性 3.無序性.
小易的老師給了小易這樣一個集合:
S = { p/q | w ≤ p ≤ x, y ≤ q ≤ z }
需要根據給定的w,x,y,z,求出集合中一共有多少個元素。小易才學習了集合還解決不了這個複雜的問題,需要你來幫助他。
輸入描述:
輸入包括一行:
一共4個整數分別是w(1 ≤ w ≤ x),x(1 ≤ x ≤ 100),y(1 ≤ y ≤ z),z(1 ≤ z ≤ 100).以空格分隔
輸出描述:
輸出集合中元素的個數
輸入例子:
1 10 1 1
輸出例子:
10
分析:
題意就是給分數判重,顯然我們不能直接算,因為浮點數是不精確的,建個結構體儲存最簡分數,然後丟進set裡就好了。
程式碼如下:
#include <iostream>
#include <set>
using namespace std;
struct Frac {
int p, q;
bool operator<(const Frac &frac) const {
if (p != frac.p) return p < frac.p;
if (q != frac.q) return q < frac.q;
return false;
}
};
int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
int main() {
int w, x, y, z;
set<Frac> s;
cin >> w >> x >> y >> z;
Frac f;
for (int i = w; i <= x; i++) {
for (int j = y; j <= z; j++) {
int div = gcd(i, j);
f.p = i / div;
f.q = j / div;
s.insert(f);
}
}
cout << s.size() << endl;
return 0;
}