Project Euler 41 - Pandigital prime Java

问题描述:

We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime.

What is the largest n-digit pandigital prime that exists?

通过分析问题,我们知道该n位数包含从1到n的数字,我们可以从大往小找。因为1-9和1-8一定是9的倍数,我们最大的数可以从7654321往下寻找,对每个数字用hashset判断和质数判断

代码如下:

    public static void main(String[] args) {
        for(int i = 7654321; i > 0; i--) {
			if(d(i) && p(i)) {
				System.out.println(i);
				break;
			}
		}
    }   
    
    public static boolean p(int n){
		HashSet set = new HashSet<Integer>();
		int max = 0;
		while(n > 0) {
			int s = n % 10;
			max = Math.max(max, s);
			if(set.contains(s))
				return false;
			set.add(s);
			n /= 10;
		}
		return max == set.size();
	}
	
	public static boolean d(int n){
		int count = 0;
		for(int i = 1; i*i <= n; i++) {
			if(n % i == 0) {
				count+= i;
			}
		}
		return count == 1;
	}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值