Satisfactory Pairs

来源:互联网 发布:知乎为什么会被邀请 编辑:程序博客网 时间:2024/06/11 00:16

Satisfactory Pairs

Problem Description

Given a positive integer, n, find and print the number of pairs of positive integers (a, b), where a < b, that exist such that the equation x * a + y * b = n (where and are positive integers) has at least one solution.

Input Format

A single positive integer denoting n.

Constraints

4 <= n <= 3 * 10^5

Output Format

Print a single integer denoting the number of such pairs.

Sample Input 0

4

Sample Output 0

2

Explanation 0

There are two such pairs: (1, 2) and (1, 3).

Submit

#include <bits/stdc++.h>using namespace std;#define MAXN 300005vector<int>factor[MAXN];//用来存储每个数字的因数int used[MAXN];//防止重复计算int cmp(int a, int b){    return a > b;}int main(){    int N;    scanf("%d", &N);    int i, j, k;    for(i = 1; i <= N; i++)//记录从1到N的每个数各有哪些因数    {        for(j = 1; j * j <= i; j++)//假如j是i的因数,那么i/j也是i的因数,所以只要j*j<=i即可        {            if(i % j == 0)            {                factor[i].push_back(j);//假如j是i的因数就存起来                if(j * j != i)//如果j不是根号i                    factor[i].push_back(i/j);//i/j也是i的因数也要存起来            }        }        sort(factor[i].begin(), factor[i].end(), cmp);//把i的因数从大到小排序    }    int ans = 0;    int a, x, by;    for(a = 1; a < N; a++)    {        for(x = 1; x * a < N; x++)        {            by = N - a * x;//by在这里是b*y应有的值            int s = factor[by].size();//by有s个因数            for(k = 0; k < s; k++)            {                if(factor[by][k] <= a)//这里的factor[by][k],也就是by的因数b                    break;                if(used[factor[by][k]] != a)//存在a不变x改变b相同的情况,所以要过滤这种情况,一旦一组(a,b)出现过,就不能出现同样的一组(a,b)                {                    used[factor[by][k]] = a;//可以理解为used[b] = a                    ans++;                }            }        }    }    printf("%d\n", ans);    return 0;}
原创粉丝点击