【等差素数列】

等差素数列

要搜索长度为10的等差素数列,可以从小到大枚举公差d,然后从小到大枚举首项p,检查p, p+d, p+2d, …, p+9d是否都是素数。

import java.util.*;

public class PrimeArithmetic {
    
    
    // 判断是否为素数
    public static boolean isPrime(int n) {
    
    
        if (n < 2) {
    
    
            return false;
        }
        int sqrt_n = (int) Math.sqrt(n);
        for (int i = 2; i <= sqrt_n; i++) {
    
    
            if (n % i == 0) {
    
    
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
    
    
        int length = 10;
        int max_d = 1000; // 公差最大值
        for (int d = 1; d <= max_d; d++) {
    
    
            for (int p = 2; p <= 10000; p++) {
    
    
                boolean is_arithmetic = true;
                for (int i = 0; i < length; i++) {
    
    
                    int num = p + i * d;
                    if (!isPrime(num)) {
    
    
                        is_arithmetic = false;
                        break;
                    }
                }
                if (is_arithmetic) {
    
    
                    System.out.println("公差为 " + d + ",首项为 " + p);
                    return;
                }
            }
        }
        System.out.println("未找到长度为 " + length + " 的等差素数列。");
    }
}

一个等差素数列的公差必须与首项互质。

解释:假设等差素数列的首项为a,公差为d,且a和d有一个大于1的共同因子p。那么,这个等差素数列中的第二项就是a+d,它也能被p整除。因此,这个等差素数列中的第二项不是素数。所以,如果一个等差素数列的公差与首项不互质,那么这个等差素数列就不可能全都是素数。

猜你喜欢

转载自blog.csdn.net/m0_60641871/article/details/129391302