1. 程式人生 > >(第五場)G max 【數論】

(第五場)G max 【數論】

inf sat pair output rod itl main 都是 ==

題目鏈接:https://www.nowcoder.com/acm/contest/143/G

題目描述

Give two positive integer c, n. You need to find a pair of integer (a,b) satisfy 1<=a,b<=n and the greatest common division of a and b is c.And you need to maximize the product of a and b

輸入描述:

The first line has two positive integer c,n

輸出描述:

Output the maximum product of a and b.

If there are no such a and b, just output -1

case1

Input:

2 4

Output:

8

說明:

a=2,b=4

備註:

1<=c,n<=10^9

題目大意:

給定兩個正整數 c,n,求一個數對 (a,b),滿足 1<=a,b<=n,且 gcd(a,b)=c
要求輸出最大的 ab
1<=c,n<=10^9

官方題解:

首先 a 和 b 一定都是 c 的倍數,如果 c<2n,那麽選 a=b=c 最優
否則選 a=(n/c)*c , b=((n/c)-1)c

大概思路:

錯誤解法:一開始打了個素數篩,因為想著gcd(a, b) = c,所以 a, b等於 c 乘以 1 或者某兩個素數,素數的範圍到 N/c;用 set 把素數存起來,然後lower_bound( ) 最接近N/c的素數,加一些判斷分支。最後果斷爆內存。

後來想一想,發現並不需要打素數表,其實腦洞一下有解的就是兩種情況 N/c == 1,理想化的最大因子為1, 所以a = b = N/c(這裏wa了幾次); N/c >= 2 ,說明 a,b不等,c 分別乘以最大(N/c)和次大((N/c)-1)。

AC code:

 1 #include <bits/stdc++.h>
 2 #define INF 0x3f3f3f3f
 3 #define ll long long int
 4 using namespace std;
 5 
 6 const int MAX_p = 1e8;
 7 ll c, N, p;
 8 
 9 int
main() 10 { 11 scanf("%lld%lld", &c, &N); 12 ll fmax_p = N/c, smax_p = 0; 13 if(fmax_p >= 1) 14 { 15 if(fmax_p == 1) printf("%lld\n", fmax_p*fmax_p*c*c); 16 else 17 { 18 smax_p = fmax_p-1; 19 printf("%lld\n", smax_p*fmax_p*c*c); 20 } 21 } 22 else 23 { 24 printf("-1\n"); 25 } 26 return 0; 27 }

(第五場)G max 【數論】