PAT乙级——1087(数组操作,辅助空间)java实现

版权声明:本文为博主原创文章,转载请注明原博客地址 https://blog.csdn.net/qunqunstyle99/article/details/84573687

题目: 有多少不同的值 (20 分)

当自然数 n 依次取 1、2、3、……、N 时,算式 n / 2 + n / 3 + n / 5 ⌊n/2⌋ + ⌊n/3⌋ + ⌊n/5⌋ 有多少个不同的值?(注: x ⌊x⌋ 为取整函数,表示不超过 x 的最大自然数,即 x 的整数部分。)

输入格式:
输入给出一个正整数 N(2 ≤ N ≤ 10​4)。

输出格式:
在一行中输出题面中算式取到的不同值的个数。

输入样例:
2017

输出样例:
1480

题目分析及实现

取整操作既可以理解为除法操作,将结果保存为int型时,会自动取整。

采用辅助空间的办法,N计算的最大值大概是 1.2 N 1.2 * N ,为了方便,将辅助数组的最大值设为了 2 N 2 * N

计算出了值后,将之对应下标位置的元素置为1,最后数一下1的个数即为结果。

import java.util.Scanner;

public class Main {
	public static void main(String []args) {
		Scanner in = new Scanner(System.in);
		int N = in.nextInt();
		in.close();
		int temp[] =new int[N*2];//辅助数组空间
		for(int i=1;i<=N;i++) {
		    //从1到N依次计算
			int count =i/2 + i/3 + i/5;
			temp[count]=1;
		}
		int time=0;
		for(int i=0;i<2*N;i++) {
			if(temp[i]==1)
				++time;
		}
		System.out.print(time);
		
	}
}

猜你喜欢

转载自blog.csdn.net/qunqunstyle99/article/details/84573687
今日推荐