给定N个随机正整数,将其中为素数的整数输出

给定N个随机正整数,将其中为素数的整数输出
例如:
输入:[3,5,11,12]
输出:[3,5,11]
注意:
1输出数组剩余元素先后顺序需要与原教
组保持一致,否则不得分。
2给出数组中不存在重复元素,无需去重

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

public class Randomsusu {
    public static void main(String[] args) throws IOException {
        BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
        String temp=stdin.readLine();//读取带空格的字符串
        String[]split=temp.split(" ");//按空格分割字符
        int N=split.length;
        int []InputArray=new int[N];
        int []OutputArray=new int[N];
        for (int i = 0; i <N ; i++) {
            InputArray[i]=Integer.parseInt(split[i]);//转为int
        }
        int flag=0;//标志位
        int suCount=0;
        for (int i = 0; i <N; i++) {
            for(int j=2;j*j<=InputArray[i];j++)
            {
                if((InputArray[i]%j)==0)
                {
                    flag++;//如果有因数,flag+1
                    break;//有因数,直接结束内层循环,减少计算量
                }
            }
            if(flag==0)//表示一直没有InputArray[i]的因数
            {
               if(InputArray[i]!=1)//1不是质数
               {
                   OutputArray[suCount]=InputArray[i];
                   suCount++;
               }
            }
            flag=0;
        }
        for (int i = 0; i < N; i++) {//也可以用i< suCount
            if(OutputArray[i]>0)//因为定义的数组长度是N,当出现0表示其后的元素都为0,不用打印输出
            {
                System.out.print(OutputArray[i]+" ");
            }
            else
            {
                break;
            }
        }
    }
}

结果展示

3 5 11 12
3 5 11 
1 3 5 9 7
3 5 7 
1 3 5 7 9 11 13 15 17 29 85 98 57 46
3 5 7 11 13 17 29 
17 85 69 3 2 5 
17 3 2 5 
  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值