[英]Given n, find how many n-digit numbers are there such that the number has prime digit at prime indices and is divisible by m?
[英]Find the greatest prime number with 7 as the last digit in {1, …, n}
假設n是250000附近的整數。使用Java,我需要找到以7結尾並屬於{1,...,n}的最大質數。 另外,我需要關注計算復雜度,並嘗試盡可能降低它。 所以我在考慮使用Eratosthenes篩子作為n,然后只檢查我的bool值數組
int start = (n % 10 < 7 ? n - (n % 10 + 3) : n - (n % 10 - 7) )
for (int i = start; i >= 0; i-= 10){
if(primes[i])
return i;
}
我想這會使整個事情變得簡單,但是我想知道哪種方法更有效。 除非有一種方法可以輕松地避免使用數組,否則我想不出任何方法。
在下面,您將找到實現Eratosthenes算法的Sieve的算法,該算法可找到1到250000之間的質數,以及如何使用它來過濾以7結尾的所有質數。
該算法的總時間復雜度為O(N),因為所有實現都以篩分算法完成。
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
int N = 250000;
ArrayList<Integer> primeWithEnding7 = new ArrayList<Integer>();
int maxPrimeNum7 = 0;
boolean[] isPrime = new boolean[N + 1];
for (int i = 2; i <= N; i++) {
isPrime[i] = false;
}
for (int i = 2; i <= N; i++) {
if (!isPrime[i]) {
int rem = i%10;
if(rem == 7) {
maxPrimeNum7 = Math.max(maxPrimeNum7, i);
primeWithEnding7.add(i);
}
for (int j = i+i; j <= N; j+=i) {
isPrime[j] = true;
}
}
}
// Print all the prime numbers ending in 7
for(int i: primeWithEnding7) {
System.out.print(i + " ");
}
System.out.println();
System.out.println("Max number is " + maxPrimeNum7);
}
}
現在讓我們舉一個例子來理解為什么這種算法對我們有用。
因此,讓我們假設N =30。現在,當循環從2開始時,如果7不是素數,則它將在內部循環j中被視為非素數,因此我達到7的事實證明它是素數,因此我保留一個全局數組列表作為數據結構,以僅添加以7結尾的質數,並且由於我使用%運算符來計算數字的最后一位,因此該步驟的時間復雜度為O(1),因此總時間該算法的復雜度為O(N)。
讓我知道,如果我在算法上犯了任何錯誤,我會修復它。
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.