1603:历届试题 幸运数

26 篇文章 0 订阅
1 篇文章 0 订阅

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		int m=sc.nextInt();
		int n=sc.nextInt();
		int[] a=new int[n];
		for(int i=0;i<a.length;i++) {
			a[i]=2*i+1;
		}
		getLuckNumber(a,1,n);
		int count=0;
		for(int i=0;i<n;i++) {
			if(a[i]>m&&a[i]<n) {
				count++;
			}
		}
		System.out.println(count);
		sc.close();
	}
	static void getLuckNumber(int[] a,int start,int end) {
		int k=start;
		int x=a[start];
		for(int i=start;i<end;i++) {
			if((i+1)%x!=0) {
				a[k]=a[i];
				k++;
			}
		}
		if(x<end) {
			getLuckNumber(a,start+1,end);
		}
	}
}

Description
幸运数是波兰数学家乌拉姆命名的。它采用与生成素数类似的“筛法”生成


首先从1开始写出自然数1,2,3,4,5,6,....

1 就是第一个幸运数。

我们从2这个数开始。把所有序号能被2整除的项删除,变为:

1 _ 3 _ 5 _ 7 _ 9 ....

把它们缩紧,重新记序,为:

1 3 5 7 9 .... 。这时,3为第2个幸运数,然后把所有能被3整除的序号位置的数删去。注意,是序号位置,不是那个数本身能否被3整除!! 删除的应该是5,11, 17, ...

此时7为第3个幸运数,然后再删去序号位置能被7整除的(19,39,...)

最后剩下的序列类似:

1, 3, 7, 9, 13, 15, 21, 25, 31, 33, 37, 43, 49, 51, 63, 67, 69, 73, 75, 79, ...

Input

输入两个正整数m n, 用空格分开 (m < n < 1000*1000)

Output

程序输出 位于m和n之间的幸运数的个数(不包含m和n)。

Sample Input

样例输入1
1 20

样例输入2
30 69

Sample Output

样例输出1
5

样例输出2
8
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;  
  
public class Main {  
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		int m=sc.nextInt();
		int n=sc.nextInt();
		ArrayList<Integer> number=new ArrayList<Integer>();
		for(int i=0;i<n+5;i++)//这里从0开始存  是为了后面求2的倍数对应位置时可以把偶数筛下来
			number.add(i);
		ArrayList<Integer> temp=new ArrayList<Integer>();
		temp.add(0);
		for(int i=1;i<number.size();i++){
			if(i%2!=0)
				temp.add(number.get(i));
		}
		int k=2;
		number=temp;
		while(true){
			int a=number.get(k++);
			temp=new ArrayList<Integer>();
			temp.add(0);
			for(int i=1;i<number.size();i++){
				if(i%a!=0)
					temp.add(number.get(i));
			}
			number=temp;
			if(a>number.size()) break;//超过范围了,肯定是无余数
		}
		int cnt=0;
		for(int i=0;i<number.size();i++){
			if(number.get(i)>m&&number.get(i)<n)
				cnt++;
			else if(number.get(i)>=n) break;
		}
		System.out.println(cnt);
	}
}  


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值