首页 > 试题广场 >

数素数 (20)

[编程题]数素数 (20)
  • 热度指数:107923 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
令Pi表示第i(i从1开始计数)个素数。现任给两个正整数M <= N <= 10000,请输出PM到PN的所有素数。

输入描述:
输入在一行中给出M和N,其间以空格分隔。


输出描述:
输出从PM到PN的所有素数,每10个数字占1行,其间以空格分隔,但行末不得有多余空格。
示例1

输入

5 27

输出

11 13 17 19 23 29 31 37 41 43<br/>47 53 59 61 67 71 73 79 83 89<br/>97 101 103
这个输出格式是真的让人恼火
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 count1=0;
      int count2=0;

     for(int i=2;i<=120000;i++)
     {
         if (issushu(i)==true)
         {
             count1++;
             if(count1>=M&&count1<N){
                 count2++;
                 if(count2%10!=0)
                 {
                     System.out.print(i+" ");
                 }
                 else
                   System.out.println(i);

             }
             if(count1==N)
             {
                 System.out.print(i);
                 break;
             }
         }


     }
    }
     public static boolean issushu(int x)
     {
         String key="true";
         if(x==1)
             return false;
         else{
             for(int i=2;i<=Math.sqrt(x);i++) {
                 if(x%i==0)
                     key="false";
             }
             if(key=="false")
                 return false;

         }
         return true;
     }
}


发表于 2021-05-14 11:48:01 回复(0)
被输出格式恶心到了
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
    private static boolean prime(long n) {
        for (long i = 2; i <= Math.sqrt(n); i++) {
            if (n % i == 0) {
                return false;
            }
        }
        return true;
    }

    private static void show(List<Long> arr) {
        for (int i = 0; i < arr.size(); i++) {
            if ((i + 1) % 10 == 0) {
                System.out.printf("%d\n", arr.get(i));
            } else {
                if (i==arr.size()-1){
                    System.out.printf("%d", arr.get(i));
                }else {
                    System.out.printf("%d ", arr.get(i));
                }

            }
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int m = sc.nextInt();
        int n = sc.nextInt();
        int count = 0;
        long i = 1;
        ArrayList<Long> list = new ArrayList<>();
        while (count <= n) {
            if (prime(i)) {
                count++;
                if (count > m) {
                    list.add(i);
                }
            }
            i++;
        }
        show(list);
    }
}

发表于 2020-09-01 15:26:46 回复(0)
挺简单的,其实就是考察审题和细心。给出java版解答:
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;

public class Main {
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        while (scanner.hasNext()) {
            int a = scanner.nextInt();
            int b = scanner.nextInt();
            
            int total = b-a+1;
            int p = 1;
            int currentNum = 0;
            int printNum = 0;
            while (true) {
                if (currentNum == b) {
                    break;
                }
                if (isSuNum(p)) {
                    currentNum++;
                    if (currentNum >= a && currentNum <= b) {
                        System.out.print(p);
                        printNum++;
                        
                        //第10个换行
                        if (printNum % 10 == 0) {
                            System.out.print("\n");
                        } else if (printNum != total) {
                            System.out.print(" ");
                        }
                    }
                }
                p++;
            }
            
        }
    }
    
    
    //判断是否素数
    private static boolean isSuNum(int num) {
        if (num == 1) {
            return false;
        }
        if (num == 2) {
            return true;
        }
        int middleNum = num / 2;
        for (int i=2; i<=middleNum; i++) {
            if (num % i == 0) {
                return false;
            }
        }
        return true;
    }
    
}


编辑于 2020-01-18 11:59:44 回复(0)
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int m = in.nextInt();
        int n = in.nextInt();
        if(n<m || n>10000) {
            System.exit(0);
        }
        int count=0;
        int out_count=0;
        int i=1;
        do{
            i++;
            boolean check = true;
            for(int j=2;j<i;j++) {
                if(i%j==0) {
                    check =false;
                    break;
                }
            }
            if(check) {
                count++;
                if(count>=m && count<=n) {
                    System.out.print(i+"");
                    out_count++;
                    if(out_count%10==0) {
                        System.out.print("\n");
                    } else if(count!=n){
                        System.out.print(" ");
                    }
                }
            }
        } while(count<=n);
    }
}
这个运行超时是什么原因 ,求解答。
发表于 2019-08-18 18:06:08 回复(0)

import java.util.Scanner;

public class Main {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int M = scanner.nextInt();
int N = scanner.nextInt();

    int sum = 0, k = 0;    
    for (int i = 1; i < 999999; i++){
        if (getPrime(i)){
            sum++;
            if (M <= sum && sum <= N ){
                System.out.printf("%d", i);
                k++;
                if (k % 10 == 0) {
                    System.out.println();
                }else {
                    System.out.print(" ");
                }
            }else if (sum > N){
                break;
            }
        }
    }
}
public static boolean getPrime(int n){
    if (n == 2) return false;
    for (int i = 2; i<= Math.sqrt(n); i++){
        if (n % i == 0){
            return false;
        }
    }
    return true;
}

}

发表于 2019-07-20 21:19:18 回复(0)
编写两个函数 :1.判断素数函数 2.计算第n个素数的函数
由于最终的输出是Pm 到 Pn内所有素数的值,故只要先计算边界 就可以很容易算出中间各个数的值
将数值保存在一个数组中,按规定输出即可
import java.util.Scanner;
/*
 * 令Pi表示第i个素数。现任给两个正整数M <= N <= 10000,请输出PM到PN的所有素数。
 */
public class Test1003 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner s = new Scanner(System.in);
        
        int M = s.nextInt();
        int N = s.nextInt();
        int[] x = new int[N-M+1];
        
        int num = 0;//表示素数个数
        int index = 0;
        int j=2;
    
                
        for(int i=M;i<=N;i++) {
            x[index] = BigPrime(i);
            index++;
        }
            
        
        int ten =0;
        for(int i1=0;i1<x.length;i1++) {
            System.out.print(x[i1]);
            ten++;
            if(ten%10==0) {
                System.out.println();
                continue;
            }
            if(i1!=(N-M)) {
                System.out.print(" ");
            }
        }
        
        
        
    }
    public static int  isSushu(int a) {//要保证判断素数算法的复杂度就得这么写
        if(a==1){
              return -1;
          }
          if(a%2==0&&a!=2){
            return -1;
          }
          for(int i=3;i<=Math.sqrt(a);i+=2){
              if(a%i==0){
                  return -1;
              } 
          }
        return 1;
    }
    
    public static int BigPrime(int n) {//计算第n个素数的值
        int result = 0;
        int count = 0;
        int x =2;
        
        while(true) {
            if(isSushu(x)==1) {
                count++;
            }
            if(count==n) {
                result = x;
                break;
            }
            x++;
        }
        return result;
    }

}

编辑于 2019-05-29 16:33:11 回复(0)
做了有点久,关键是运行超时,我就把循环改掉了一部分,以下是我最开始的编程及修改后的
(1)运行超时,循环增大了程序的复杂度
import java.util.Scanner;
public class test03 {

    /**
     * @param arg***r />      */
    public static void main(String[] arg***r />         // TODO Auto-generated method stub
        Scanner sc=new Scanner(System.in);
        short M=sc.nextShort();
        short N=sc.nextShort();
        int su[]=new int[N];
        su[0]=2;    
        for(int j=3,i=1;i<N;j++)
        {
            int f=1;
            for(int k=2;k<j&&f==1;k++)
            {
                int b=j%k;
                if(b==0)
                    f=-1;
            }
            if(f==1)
            {
                su[i]=j;
                i++;
            }
        }
        for(int j=M-1;j<N-1;j++)
        {
            System.out.print(su[j]+" ");
            if((j-M+2)%10==0)
            {System.out.println();}
        }
        System.out.print(su[N-1]);
    }
}

(2)修改后
import java.util.Scanner;
public clas***ain {

    /**
     * @param arg***r />      */
    public static void main(String[] arg***r />         // TODO Auto-generated method stub
        Scanner sc=new Scanner(System.in);
        int M=sc.nextInt();
        int N=sc.nextInt();
        
        int x1=0;
        int x2=0;
        for(int k=2;x1<=N;k++)
        {
            int f=1;
            for(int i=2;i<=Math.sqrt(k);i++)
            {
                if(k%i==0)
                    f=-1;
            }
            if(f==1)
            {
                x1++;
                if(x1>=M&&x1<=N)
                {
                    if(x2==9)
                    {
                        System.out.println(k);
                        x2=0;
                    }
                    else if(x1!=N)
                    {
                        System.out.print(k+" ");
                        x2++;
                    }
                    else
                    {
                        System.out.println(k);
                    }
                }
            }
        }
        
    }
}

发表于 2019-05-21 16:44:26 回复(0)
终于把答案凑出来了
1——行末不能有空格!!!最后一个数字后面也是!!!
2——第10000个不能不返回0
3——不能超时,不能狂求出很多素数
import java.util.ArrayList; import java.util.Scanner;  public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in);  int M = scanner.nextInt();  int N = scanner.nextInt();   ArrayList<Integer> list = guessSushu();    if (M>N||(N-M)>list.size()){ System.out.print(0);  }else { int j = 0;  for (int i = M-1; i < N ; i++) { j++;  if (j==N-M+1){ System.out.print(list.get(i));  }else { if (j%10!=0){ System.out.print(list.get(i)+" ");  }else { System.out.print(list.get(i)+"\n");  }
                }
            }
        }
    } public static ArrayList<Integer> guessSushu() { ArrayList<Integer> list = new ArrayList<>();   int suShu = 2;  while (suShu <= 104729) { int flag = 0;  for (int i = 2; i <= Math.sqrt(suShu); i++) { if (suShu % i == 0) { flag = 1;  }
            } if (flag == 0) { list.add(suShu);  } suShu++;  } for (int i = list.size()+1; i <100000 ; i++) { list.add(0);  } return list;  }
}

发表于 2019-05-15 14:51:59 回复(1)
①这题比较难受的就是我以为是在10000以内的素数结果是在10000项内素数
②可以利用迭代器优化直接用链表.get的时间。但是用数组可能会更快。(没试数组)
总之代码还能优化,至少可以从第M项素数时再添进去。
③格式问题

import java.util.Iterator;
import java.util.LinkedList;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {    
        LinkedList<Integer> list = new LinkedList<Integer>();
    for(int i=1;list.size()<=10000;i++) {
        if(find(i))list.add(i);
        }
    Scanner sc = new Scanner(System.in);
    Iterator it = list.iterator();
    int M = sc.nextInt();
    int N = sc.nextInt();
    for(int i=0;i<M;i++)if(it.hasNext())it.next();
    for(int i=0;i<=N-M;i++) {
        if(it.hasNext()) {
        System.out.print(it.next());
        if(i<N-M) {
            if((i+1)%10==0)System.out.println("");
            else System.out.print(" ");
        }
        }
    }
    }
    public static boolean find(int x) {
        for(int i=2;i<x;i++) {
            if(x%i==0)return false;
        }
        return true;
    }
}
 
发表于 2019-04-03 12:06:03 回复(0)
import java.util.Scanner;
public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            int pm = sc.nextInt();
            int pn = sc.nextInt();
            int count = 1; // 统计数到了第几个素数
            int cur = 2;
            int i = 1;   // 统计输出了多少素数
            while(count<=pn){
                if(isPrime(cur)){
                    if(count >= pm){
                        System.out.print(cur);
                        if(i%10 == 0){
                            System.out.println();
                            i++;
                        }else{
                            if(count < pn){
                                System.out.print(" ");
                                i++;
                            }else{
                                ;
                            }
                        }
                        
                    }
                    count++; // 是素数,就考虑“是否要输出,如何输出”,然后找下一个素数
                    cur++;   // 用cur来挨个遍历每一个正整数
                }else {
                    cur++; // 不是素数,就下一个
                }
            }
        }
    }
    static boolean isPrime(int k){
        int i = 2;
        while(i * i <= k){
            if(k%i == 0){
                return false;
            }else {
                i++;
            }
        }
        return true;
    }
}

发表于 2019-03-17 10:57:43 回复(0)
import java.util.Scanner;
public class Main {
 private static int isprime(int n) {
  int a=1;
  if(n<2) {
   a=0;
  }
  if(n%2==0) {
   a=0;
  }
  for(int i=3;i<=Math.sqrt(n);i+=2) {
   if(n%i==0) {
    a=0;
   }
  }
  return a;
 }
 public static void main(String[] args) {
  Scanner in=new Scanner(System.in);
  int n=in.nextInt();
  int m=in.nextInt();
  if(m==1&&n==1) {
   System.out.println(2);
  }
  else {
  int []num=new int [m];
  num[0]=2;
  num[1]=3;
  int a=2;
  for(int i=5;a<m;i+=2) {
   if(isprime(i)==1) {
    num[a]=i;
    a++;
   }
  }
  for(int i=n-1;i<num.length;i++) {
   if((i-n+2)%10==0&&i!=n-1||i==num.length-1) {
    System.out.println(num[i]);
   }
   else {
   System.out.print(num[i]+" ");
  }
  }
 }
}
}

发表于 2019-03-06 22:59:06 回复(0)
public static void main(String[] args) throws IOException {
  int start=sc.nextInt();
  int end=sc.nextInt();
        sc.close();
  int[] prime=new int[end];
  int i=0;
  int num=2;
  int count=0;
  while (i<end) {
   boolean flag=true;
   if (num==2) {flag=true;}
   else {
    for (int j = 0; j <prime.length;j++) {
     try {if(num%prime[j]==0) {flag=false;break;}}
     catch (Exception e) {break;}
    }
   }
   if (flag) {
    prime[i]=num;
    i++;
   }
   num++;
  }
  for (int j = start-1; j <end; j++) {
   System.out.print(prime[j]);
   count++;
   if (count%10==0 && j!=end-1) {
    System.out.println();
   }
   else if (count%10!=0 && j!=end-1) {
    System.out.print(" ");
   }
  }
 }
发表于 2018-11-14 17:39:57 回复(0)
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
//        numberClassify();
//        System.out.println(getNextPrimeFrom(3));
        getPrimesFromM2N();
    }
    
    static void getPrimesFromM2N() {
        Scanner scanner = new Scanner(System.in);
        int m = scanner.nextInt();
        int n = scanner.nextInt();
        int i = 0;
        int prime = 1;
        while (i < m - 1) {
            i++;
            prime = getNextPrimeFrom(prime);
        }
//        int[] primes = new int[10];
        for (int j = 1; j <= n - m + 1; j++) {
            prime = getNextPrimeFrom(prime);
            if (j == 1) {
                System.out.print(prime);
                continue;
            }
            if (j % 10 == 1) {
                System.out.println();
                System.out.print(prime);
            } else {
                System.out.print(" " + prime);
            }
        }
    }

    static int getNextPrimeFrom(int prime) {
        int nextPrime = prime;
//        boolean hasGetNext = false;
        label:
        while (true) {//!hasGetNext
            nextPrime++;
            for (int i = 2; i <= Math.sqrt(nextPrime); i++) {
                if (nextPrime % i == 0) {
                    continue label;
                }
            }
            break;
//            hasGetNext = true;
        }
        return nextPrime;
    }
}

发表于 2018-06-04 21:14:27 回复(0)
八个用例通过了七个,一直有一个说我下标越界,求大佬帮我看看怎么改
import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int num1 = scan.nextInt();
        int num2 = scan.nextInt();
        ArrayList<Integer> al = new ArrayList<Integer>();
        for (int j = 1; j <= 15000; j++) {
            if (isPrime(j))
                al.add(j);
        }
        int count = 0;
        for (int st = num1; st <= num2; st++) {
                System.out.print(al.get(st));
                count++;
            if(count%10!=0 && count!=(num2-num1+1))
                System.out.print(" ");
            else if(count % 10 == 0)
            {
                System.out.println();
            }
                
        }
    }

    public static boolean isPrime(int n) {
        if (n < 3)
            return true;
        for (int i = 2; i < n; i++) {
            if (n % i == 0)
                return false;
        }
        return true;
    }
}

发表于 2018-04-11 20:33:06 回复(1)
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
    Scanner sc=new Scanner(System.in);
    int M,N;
    int fl=0;
    int b=0;
    M=sc.nextInt();
    N=sc.nextInt();
//遍历数
    for(int j=2;b<=N;j++){
        int count=0;
//遍历数字,并判断是否是素数
        for(int i=2;i<=Math.sqrt(j);i++){
            if(j%i==0){
                count++;
                break;
            }
        }
        if(count==0){
            b++;
            if(b>=M&&b<=N){
                fl++;
                System.out.print(j);
                if(fl%10==0||b==N){
                    System.out.println();
                }
                else{
                    System.out.print(" ");
                }
            }
        }
    }
    sc.close();
    }
}

发表于 2018-02-10 14:05:53 回复(0)
import java.util.*;
import static java.lang.System.*;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int start = sc.nextInt();
        int end = sc.nextInt();
        int count = 0;
        int next = 0;
        for (int num = 2; num < Integer.MAX_VALUE; num++) {
            if (isPrime(num)) {
                count++;
                if (count >= start && count <= end) {
                    next++;
                    if (next == end - start + 1)
                        out.print(num);
                    else if (next % 10 == 0)
                        out.println(num);
                    else
                        out.print(num + " ");
                }
                if (count > end) break;
            }
        }
    }
    private static boolean isPrime(int n) {
        if (n < 2) return false;
        if (n == 2) return true;
        for (int i = 2; i <= Math.sqrt(n); i++)
            if (n % i == 0) return false;
        return true;
    }
}

发表于 2017-12-02 20:39:15 回复(0)
复杂度太高了,唉~~
import java.util.Scanner;

public class Main {     @SuppressWarnings("resource")     public static void main(String[] args) {         Scanner in = new Scanner(System.in);         int M = in.nextInt();// 这是左边界         int N = in.nextInt();// 这是右边界         int n;// 这是第一层循环的开平方,为了减少时间复杂度         boolean flag;// 这是判断是否是素数的小旗子         /**          * 刚才把题意理解错了,本来是第多少个到第多少个素数,一直理解成多少到多少之间的素数          */         int suShuCount = 0;// 这里统计目前是第几个素数         int changeLineVariable = 0;// 这里是换行的统计         for (int i = 2; i > 0; i++) {             n = (int) Math.sqrt(i);             flag = true;             for (int j = 2; j <= n; j++) {                 if (i % j == 0) {                     flag = false;// 这就是合数,不是质数                     break;                 }             }             if (flag) {                 suShuCount++;                 if (suShuCount >= M && suShuCount < N) {                     System.out.print(i + " ");                     changeLineVariable++;                     if (changeLineVariable % 10 == 0) {                         System.out.println();// 换行的方法                     }                 } else if (suShuCount == N) {                     System.out.print(i);// 最后一个数字输出之后不在序号空格                 }             }         }     }

}

发表于 2017-09-18 16:48:34 回复(0)
这边AC,PAT那边超时。算法没问题,就是java太慢了,我要转c++。。
--------------
重新提交一次。
估计是被我吓到了,运行时间直接打对折,AC。
PAT的系统真心很玄学,考试的时候还是别用java了,负载一大直接跪。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        String[] temp = input.readLine().split("\\s+");
        input.close();

        int low = Integer.parseInt(temp[0]), high = Integer.parseInt(temp[1]);
        if (low <= 0 || high > 10000 || high < low) {
            System.exit(0);
        }
        int[] prime = getPrime(low, high);
        printer(prime, low, high);
    }

    private static int[] getPrime(int low, int high) {
        int[] primes = new int[high];
        int count = 0;
        for (int i = 2; count < high; i++) {
            if (isPrime(i, primes)) {
                primes[count++] = i;
            }
        }

        return primes;
    }

    private static boolean isPrime(int num, int[] primes) {
        if (num == 2 || num == 3)
            return true;
        if (num % 2 == 0)
            return false;
        int bound = (int) Math.sqrt(num);
        for (int i = 0; primes[i] <= bound; i++) { // https://program-think.blogspot.com/2011/12/prime-algorithm-1.html             if (num % primes[i] == 0) {
                return false;
            }
        }
        return true;
    }

    private static void printer(int[] a, int low, int high) {
        int ten = 0 , bound = high - 1;

        for (int i = low - 1; i < high; i++) {
            System.out.print(a[i]);
            ten++;
            if (ten %10 == 0) {
                System.out.println();
                continue;
            }
            if (i != bound) {
                System.out.print(" ");
            }

        }

    }
}
编辑于 2017-09-15 08:32:34 回复(0)
import java.util.ArrayList;  import java.util.Scanner;

public class Main4 {
	public static void main(String[] args) {
		int M, N;
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入第M个素数和第N个素数的位置:");
		M = sc.nextInt();
		N = sc.nextInt();
		int num = 2;
		int sum = 0;
		int j=0;
		while (true) {
			if (numberIsPrimer(num) == true) {
				sum++;
				if (sum >= M && sum <= N) {
					if ((j % 10) == 0) {
						System.out.print(num);
					} else if ((j % 10) != 0 && (j % 10) != 9) {
						System.out.print(" " + num);
					} else {
						System.out.println(" " + num);
					}
					j++;
				}
			}
			num++;
			if (sum > N)
				break;
		}
	}

	public static boolean numberIsPrimer(int n) {
		for (int i = 2; i <=n/2; i++) {
			if ( n % i == 0) {
				return false;
			}
		}
		return true;
	}
}


发表于 2017-08-18 23:49:35 回复(0)

问题信息

难度:
31条回答 49741浏览

热门推荐

通过挑战的用户

数素数 (20)