声网日常实习C++笔试题:求数组的最大公约数

题目描述:
Let’s consider all in the range from 1 to n(inclusive).
Among all pairs of distinct integers in this range, find the maximum possible greatest common divisor of integers in pair. Formally, find the maximum value of gcd(a ,b), where 1 ≤ \leq a ≤ \leq b ≤ \leq n.
The greatest common divisor, gcd(a, b), of two positive integers a and b is the biggest integer that is a divisor of both a and b.

输入描述:
The first line contains a single integer t (1 ≤ \leq t ≤ \leq 100) - the number of test cases. The description of the test cases follows.The only one line of each test case contains a single integer (2 ≤ \leq n ≤ \leq 106) .

输出描述:
For each test case, output the maximum value of gcd(a, b) among all 1 ≤ \leq a ≤ \leq b ≤ \leq n.

首先给出最终的AC通过结果代码:

#include <iostream>
using namespace std;
int main(){
	int NumOfInput; //输入的个数
	cin >> NumOfInput;
	
	while(NumOfInput--){
		int MaxNum;
		cin >> MaxNum; //n的最大值
		
		if(MaxNum % 2 == 0)
			cout << MaxNum / 2 << endl;	
		else
			cout << (MaxNum-1) /2 << endl;
	}	
	return 0;	
}

分析:

  • 题目看起来比较复杂,总结为一句话“求最大公约数的最大值”。 最常用的求两个数的最大公约数的求法为辗转相除法,其实现代码如下:
int GreaComDiv(int a, int b){
	int c = b;	
	while(a%b != 0){
		c = a % b;
		a = b;
		b = c;
	} 
	return c;
}
  • 求是最大公约数的最大值,即转为求2与n或者n-1的最大公约数,理解了这个之后接下来就简单啦,直接往上套就可以了!

总结:

  • 求最大公约数的最大值,可以把问题转化为为求最小值和最大值的最大公约数。
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值