题目描述:
当自然数 n 依次取 1、2、3、……、N 时,算式 ⌊n/2⌋+⌊n/3⌋+⌊n/5⌋ 有多少个不同的值?(注:⌊x⌋ 为取整函数,表示不超过 x 的最大自然数,即 x 的整数部分。)
输入格式:
输入给出一个正整数 N(2≤N≤104)。
输出格式:
在一行中输出题面中算式取到的不同值的个数。
输入样例:
2017
输出样例:
1480
解题思路:
求有多少种不同的情况,所以不能有重集,正好可以应用哈希表求解。
解法一:用数组模拟哈希表,直接开一个大数组,存放不同的解,注意至少要开到10334以上。
解法二:用现成的set集合存放不同解。
注意无论用那种解法,尽管只有一个输入,也要用BufferedReader读取,否则一定会超时!
数组代码:
import java.io.*;
public class Main {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int []arr = new int[10400];
int count = 0;
for(int i = 1; i <= n;i++) {
int temp = i / 2 + i / 3 + i / 5;
if(arr[temp] == 0) {
arr[temp]++;
count++;
}else {
continue;
}
}
System.out.println(count);
}
}
提交截图:
set代码:
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
Set<Integer> set = new HashSet<Integer>();
for(int i = 1; i <= n;i++) {
int temp = i / 2 + i / 3 + i / 5;
if(set.contains(temp)) {
continue;
}else {
set.add(temp);
}
}
System.out.println(set.size());
}
}
提交截图: