[英]Finding prime numbers in an array of 10 numbers
Once I took from the user 10 numbers and placed them in an array of size 10, I want to check for each number in the array if it is prime or not and count how many prime numbers there is.一旦我从用户那里取出 10 个数字并将它们放入一个大小为 10 的数组中,我想检查数组中的每个数字是否为质数,并计算有多少个质数。 Here is what I tried to do:这是我试图做的:
int count=0;
for(int r=0;r<10;r++) {
for(int t=2; t < array[r];t++) {
if(array[r] % t != 0) {
count++;
}
}
}
array[r] is already filled with numbers at this point, so all I need to do is to check for each number if it is prime or not. array[r] 此时已经填满了数字,所以我需要做的就是检查每个数字是否为质数。
Here is another way you can check for prime numbers.这是检查素数的另一种方法。 It does not increment by 1, so it is faster.它不会增加 1,因此速度更快。
int count=0;
for(int r=0;r<10;r++){
if (isPrime(array[r])) count++;
}
And the method:和方法:
public static boolean isPrime(int n) {
if(n < 2) return false;
if(n == 2 || n == 3) return true;
if(n%2 == 0 || n%3 == 0) return false;
int sqrtN = (int)Math.sqrt(n)+1;
for(int i = 6; i <= sqrtN; i += 6) {
if(n%(i-1) == 0 || n%(i+1) == 0) return false;
}
return true;
}
int a[] = {0,1,2,3,4,5,6,7,8,9};
int count=a.length;
boolean flag=true;
for(int i=0;i<a.length;i++)
{
for(int j=2;j<a[i];j++)
{
if(a[i]%j==0)
{
flag=false;
break;
}
}
if(flag==false)
{
count--;
}
}
System.out.println(count);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.