牛客想開了大賽2(Java版)

A:鏈接:https://ac.nowcoder.com/acm/contest/907/A
來源:牛客網

小a的平面上有n個X型不明物體,但是他不確定他們的位置。現在請你來確定他們的位置,使得劃分形成的平面儘量多
思路代碼裏,就是找規律,推公式
AC代碼:



import java.util.Scanner;
//公式,可以先通過一條直線,2條直線,3條直線找規律
//一條直線:2塊;
//兩條直線:4塊;
//三條直線:7塊;
//四條直線:11塊;
//推出n>1時,f[n]=f[n-1]+n;
/*f(n)=f(n-1)+n
=f(n-2)+(n-1)+n
……
=f(1)+1+2+……+n
=n(n+1)/2+1*/
//f=(n/2)*(n+1)+1
public class Main {
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		long n=sc.nextLong();
		System.out.println(n*(2*n+1)+1);
		sc.close();
	}
}

B:
t次詢問,每次給你一個數n,求在[1,n]內約數個數最多的數的約數個數

鏈接:https://ac.nowcoder.com/acm/contest/907/B
來源:牛客網

對於100%的數據,t <= 500 , 1 <= n <= 1000000000000000000
AC代碼:

import java.util.Scanner;
/*首先給出一個簡單的求因子個數的公式
設n=p1^k1*p2^k2*……*pn^kn,其中p1,p2,……,pn爲互不相同的質數,k1,k2,……,kn爲正整數(這叫n的標準分解)
則n所有正約數個數爲(k1+1)(k2+2)*……*(kn+1)個
15464=2^3*1933
正約數爲(3+1)*(1+1)=8個
然後給出一個溢出的相關的知識:當整型數據超出取值範圍時 數據呈環形變化 例如32767 + 1 = -32768 36767 +2 = -32767
因爲比較情況比較複雜,於是本題防溢出的方式不是這個。。。
*/
public class Main {
	static int p[]={0,2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,51};
	static long ans,n;
	static long pow(int x,int y){
		long res=1;
		for(int i=1;i<=y;i++){
			res*=x;
		}
		return res;
	}
	static void dfs(int pos,long num,long sum,int len){//pos爲當前所選素數位置,num爲當前約數個數,i爲當前素數個數
		if(sum>n)
			return;
		if(sum<=n)
			ans=Math.max(ans, num);
		for(int i=1;i<=len;i++){
			long res=pow(p[pos],i);
			if(sum>n/res)
				break;
			dfs(pos+1,num*(i+1),sum*res,i);
		}
	}
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		int t=sc.nextInt();
		while(t-->0){
			n=sc.nextLong();
			ans=0;
			dfs(1,1,1,30);
			System.out.println(ans);
		}
		sc.close();
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章