超时不会改了

P1217 [USACO1.5] 回文质数 Prime Palindromes

zhouchangzhe @ 2024-08-06 10:15:00

package luogu;

import java.util.Scanner;
import java.util.Arrays;
public class p1271回文质数 {
public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
    long l=sc.nextLong();
    long r=sc.nextLong();
    boolean []a=new boolean [100000001];
    Arrays.fill(a,true);
    a[1]=false;
    a[0]=false;
    for(long i=2;i<r/i;i++)
    {
        if(a[(int)i])
        {
            for(int j=2;j*i<=r;j++)
            {
                a[(int)(i*j)]=false;
            }
        }
    }

    for(long i=l;i<=r;i++)
    {
        if(a[(int)i]&&huiwen(i))
        {
            System.out.println(i);
        }
    }
    sc.close();
}

public static boolean huiwen(long n)
{
    long l=n,r=0;
    while(n!=0)
    {
        r=r*10+n%10;
        n=n/10;
    }
    return l==r;
}

}

大佬们这个超时怎么改,求qwq


by Ahws_rwhy @ 2024-08-06 10:21:35

@Djy3143664540

您看看,c++ 的。

#include <bits/stdc++.h>

using namespace std;

const int N = 1e7;

//bool Is_Prime(int a) {

//  if(a == 0 || a == 1) return 0;

//  if(a == 2) return 1;

//  for(int i = 2; i <= sqrt(a);i++) {

//      if(!(a%i)) return 0;

//  }

//  return 1;

//}

bool f[N];

int prime[N + 1];

int cnt;

void Is_Prime(int a) {

//  memset(prime, 1, sizeof(prime));

    for (int i = 2; i <= a; i++) {

        if(!f[i]) prime[cnt ++] = i;

    for(int j = 0; prime[j] <= a / i;j ++) {

        f[prime[j] * i] = 1;

        if(i % prime[j] == 0) break;

    }

    }

//  for (int i = 2; i <= n; i ++) {

//      if (prime[i]) cout << i << " ";

//  }

}

bool check(int i) {

    int f1 = 0;

    string s = to_string(i);

    int l = 0, r = s.size() - 1;

    while (l < r) {

        if (s[l] != s[r]) return 0;

        l += 1, r -= 1;

    }

//      if(f1 == 0) return 0;

    return 1;

}

int L, R;

//int f = 1;

int p;

int main() {

    cin >> L >> R;

    Is_Prime(N - 1);

    for (int i = 0; i < cnt; i++) {

        p = prime[i];

        if(p >= L && p <= R && check(p)) {

            cout << p << endl;

        }

    }

    return 0;

}

by zhouchangzhe @ 2024-08-06 11:43:48

@rwhy AC了谢谢佬


|