存放素数数组JAVA_java – 返回素数数组

我需要一个方法来返回数组中的素数.

所以如果给出:primeArray(5)

比这样的数组应该返回:(2,3,5)

出于某种原因,这对我来说似乎不起作用:

public static int[] primeArray(int numFind)

{

//determines the size of the array returned

int primeTotal = 0;

//loop to find total prime numbers

for (int j = 1; j <= numFind; j ++)

{

if (isPrime(j))

primeTotal +=1;

}

//declare array to be returned

int[] numA = new int[primeTotal];

//current index of prime number

int iP = 0;

//loop to add prime elements to array

for (int x = 1; x <= numFind; x ++)

{

if (isPrime(x))

{

numA[iP]=x;

iP++; //

}

}

return numA;

}

public static boolean isPrime(int n)

{

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

{

if(n%i==0)

return false;

}

return true;

}

这就是我用来测试我的代码:

int[] num = primeArray(11);

System.out.println(num[0]);

System.out.println(num[1]);

但是对于输出我得到了这个:

1

2

但是,如果我评论出iP;比if语句最终决定只在素数作为参数传递时才执行:isPrime(j)但是如果违反了primeArray方法的全部目的,因为我需要primeArray方法来返回素数数组.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值