Java 返回一个素数数组
我需要一个方法来返回数组中的素数 因此,如果给定:primeArray(5) 这样的数组应该返回:(2,3,5) 出于某种原因,这似乎对我不起作用:Java 返回一个素数数组,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 =
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++; // <--- THIS IS CAUSING ME PROBLEMS
}
}
return numA;
}
public static boolean isPrime(int n)
{
for (int i = 2; i < n; i++)
{
if(n%i==0)
return false;
}
return true;
}
但对于输出,我得到如下结果:
1
2
然而,如果我注释掉iP++;if语句最终决定仅在以下情况下执行:isPrime(j)中的素数作为参数传递,但是if违背了primeArray方法的全部目的,因为我需要primeArray方法返回素数数组。您只需对第一个数组值进行输出 只需替换输出
for(int i = 0; i < num.length; i++)
{
System.out.println(num[i]);
}
for(int i=0;i
您的代码运行良好。在您的isPrime()
方法中,在末尾添加这条语句
if(n<2)返回false代码>
我认为以目前的方式,当1通过时,你会得到一个正确的答案
我能想到的另一个建议是,如果你期望你的限制很小,你可以使用一个静态表来处理一些数字
static int[]PRIME_TABLE={2,3,5,7,11,13,17,19,23,29,31}代码>等
因此,在本例中,当限制小于32时,您不需要计算它下面的所有素数,只需循环此表并返回这些数字。您的isPrime()
方法有故障。对于number<2
,您需要返回false
。此外,您不需要迭代到n,只需迭代到n/2,甚至更好地sqrt(n)
将其更改为:
public static boolean isPrime(int n) {
if (n < 2) return false;
int maxIteration = Math.ceil(Math.sqrt(n));
for (int i = 2; i < maxIteration; i++) {
if(n % i == 0)
return false;
}
return true;
}
然后您可以只返回素数,并将方法的返回类型更改为List
,而不是int[]
public static List<Integer> primeNumberList(int numFind)
公共静态列表primeNumberList(int numFind)
如果确实要返回int[]
,则需要将ArrayList
转换为int
数组。我把这个任务交给你。只需搜索这个就可以了,你会得到太多的帖子
另外,如果要生成所有素数直到一个非常大的数,那么您应该看看我试图以一种稍微不同的方式编写isPrime(int num)函数。代码变得有点复杂
冗长但有效。我使用了不同的逻辑来确定数字是否为1,因为1既不是素数也不是复合数。代码如下
static int count=0;
static boolean flag;
public static boolean isPrime(int num){
for(int i = 1; i<=num/2 ; i++){
if(num%i ==0){
count++;
if(count >=2){
flag = false;
}
else{
if( num/1==1){
flag = false;
}
else{
flag = true;
}
}
}
}
return flag;
}
static int count=0;
静态布尔标志;
公共静态布尔值isPrime(int num){
对于(int i=1;i=2){
flag=false;
}
否则{
如果(num/1==1){
flag=false;
}
否则{
flag=true;
}
}
}
}
返回标志;
}
此代码返回所有小于n的素数
public ArrayList<Integer> allPrimesLessThanN( int n) {
int sqrtN = (int)Math.sqrt(n);
int [] numberList = new int[n];
ArrayList<Integer> primeList = new ArrayList<>();
for( int i = 0; i < n ; i++)
{
numberList[i] = i+1;
}
int k = 2;
while( k <= sqrtN)
{
if(numberList[k+1] != 0)
{
for( int j = k+1; j < n; j++)
{
if( numberList[j] % k == 0)
{
numberList[j] = 0;
}
}
}
k++;
}
for( int i = 1; i < n; i++)
{
if(numberList[i] != 0)
primeList.add(numberList[i]);
}
return primeList;
}
public ArrayList allprimeslsthann(int n){
intsqrtn=(int)Math.sqrt(n);
int[]numberList=新的int[n];
ArrayList primeList=新的ArrayList();
对于(int i=0;i 虽然(k有几种方法可以获得素数数组,但最简单的计算方法是使用一个Eratosthenes筛。这会迭代每一个递增的数,当找到下一个素数时,所有随后的倍数都标记为非素数。大多数实现使用布尔数组,如下所示:
boolean[] numbers = new boolean[max];
// At first, assume every number is prime
for (int i = 0; i < max; i++)
numbers[i] = true;
// Zero and one are not primes
numbers[0] = number[1] = false;
// Begin iteration from 2, the smallest prime
for (int i = 2; i < max; i++) {
// if i is prime, all multiples of i are not prime
if (numbers[i]) {
for (int j = i * 2; j < max; j += i) {
numbers[j] = false;
}
}
}
现在您可以使用Primes.isPrime(…)
检查;)公共类演示{
公共静态void main(字符串[]args){
int result[]=ArrayOfPrimeNumbers(30);
for(int i=0;i 对于(inti=2;i,您可以通过使用筛选算法来查找素数,从而对其进行更多优化。下面的实现可以查找高达(10^9)-1的素数
#包括//用于I/O
#包含//以保持素数
#包含//用于sqrt()
#定义lli长整型
使用名称空间std;
vectorprime;//使用long-long int数据类型获取相对较大数字的结果……如果使用较小的数字,则可以使用int。
lli高达;
bool stat[100000001];//跟踪素数/非素数的状态数组(0=素数,1=非素数,最初都是0)
空隙筛(lli至)
{
lli n=高达;
stat[0]=stat[1]=1;//标记0和1,因为它们不是素数
对于(lli i=4;i)您的代码看起来很好..只需循环数组..我还记得有一种方法可以预先告诉将有多少个素数。+1,但请注意Math.ceil(Math.sqrt(n))
最好是在循环之外,而不是每一步都计算它
public ArrayList<Integer> allPrimesLessThanN( int n) {
int sqrtN = (int)Math.sqrt(n);
int [] numberList = new int[n];
ArrayList<Integer> primeList = new ArrayList<>();
for( int i = 0; i < n ; i++)
{
numberList[i] = i+1;
}
int k = 2;
while( k <= sqrtN)
{
if(numberList[k+1] != 0)
{
for( int j = k+1; j < n; j++)
{
if( numberList[j] % k == 0)
{
numberList[j] = 0;
}
}
}
k++;
}
for( int i = 1; i < n; i++)
{
if(numberList[i] != 0)
primeList.add(numberList[i]);
}
return primeList;
}
boolean[] numbers = new boolean[max];
// At first, assume every number is prime
for (int i = 0; i < max; i++)
numbers[i] = true;
// Zero and one are not primes
numbers[0] = number[1] = false;
// Begin iteration from 2, the smallest prime
for (int i = 2; i < max; i++) {
// if i is prime, all multiples of i are not prime
if (numbers[i]) {
for (int j = i * 2; j < max; j += i) {
numbers[j] = false;
}
}
}
boolean isPrime(double p) {
if (p < 2) return false;
for (int i = 2; i <= Math.sqrt(p); i++) if (p % i == 0) return false;
return true;
}
class Primes {
private static final List<Double> known_primes = new ArrayList<Double>(Collections.singletonList(2d));
public static boolean isPrime(double p) {
if (p < 2) return false; // 2 already in our cache
if (known_primes.contains(p)) return true; // found prime in cache
for (double i = 3; i <= Math.sqrt(p); i += 2) { // only check odd numbers
if (!isPrime(i)) continue; // only check primes
if (p % i == 0) return false; // p is divisible by i, so not prime
}
// checked all possible divisors, so p must be prime - cache and sort it!
known_primes.add(p);
Collections.sort(known_primes);
return true;
}
}
public class Demo {
public static void main(String[] args) {
int result[] = ArrayOfPrimeNumbers(30);
for (int i = 0; i < result.length; i++) {
System.out.println("Factor: " + result[i]);
}
}
public static int[] ArrayOfPrimeNumbers(int n) {
int countPrimeNumbers = 0;
for (int i = 2; i <= n; i++) {
if (isPrime(i)) {
countPrimeNumbers++;
}
}
int newArrayofPrime[] = new int[countPrimeNumbers];
int count = 0;
while (count < countPrimeNumbers) {
for (int i = 2; i <= n; i++) {
if (isPrime(i)) {
newArrayofPrime[count] = i;
count++;
}
}
}
return newArrayofPrime;
}
public static boolean isPrime(int n) {
if (n <= 1)
return false;
for (int i = 2; i < n; i++)
if (n % i == 0)
return false;
return true;
}
#include<iostream>//for I/O
#include<vector>//for keeping primes
#include<math.h>//for sqrt()
#define lli long long int
using namespace std;
vector<lli>prime;//using long long int data type for getting result for relatively bigger numbers...you may use int if you are working with smaller numbers.
lli upto;
bool stat[100000001];//Status array to keep track for primes/non-primes (0=prime, 1=non-prime, initially all are 0)
void sieve(lli upto)
{
lli n=upto;
stat[0]=stat[1]=1;//Marking 0 and 1 as they are not primes
for(lli i=4;i<=n;i+=2)//Marking all even numbers as they won't be primes
{
stat[i]=1;
}
lli sqrtn=sqrt(n);
//You can check if a number is prime or not just by making sure it is not divisible by any numbers upto it's square-root.
//The reason of not checking the numbers after that is that if the number is divisible by a number greater than or equal to its square-root,
//then we surely have already found another number which also divides the number less than or equal to its square root. For example to check if 36 is
//a prime we can try dividing it with numbers <=sqrt(36) or <=6.We need not go beyond it. Say we need not check with 9 or 12 etc. as we have already checked
//the divisibility with their conjugates 4 and 3 respectively (as 4*9=36 and 3*12=36) and found that 36 is getting divided, hence non prime.
for(lli i=3;i<=sqrtn;i+=2)//So continuing this loop upto sqrt(n) and starting from 3 and stepping to only the odd numbers,as we cannot expect an even number to be a prime (except 2)
{
if(stat[i]==0)//ith index is still unmarked means it is a prime
{
//..so leaving ith index unmarked we are marking all the multiples of i as number i will divide them and they won't be primes.
//But again we can do some optimizations:
//(1) The next unmarked number divided by i, greater than i will be i*i. Because numbers less than i*i which is also divided by i are already marked by some numbers<i. An example will make it clear:
// Say for 5 we will start marking from 5*5=25, although 15 is divided by 5 but we need not mark it again as it is already marked by 3 (as 3 also divides 15) when we worked with 3.
//(2) We are advancing our checking 2*i times as we are now searching for primes in odd numbers only, so we are skipping the marking for even numbers (say for 3, starting check from 3*3=9, we will next check 9+2*i=9+2*3=15 (we skipped checking 12 as it is even and we have already marked all even numbers initially (except 2) for being non-primes).
for(lli j=i*i;j<=n;j+=2*i)
{
stat[j]=1;//so marking the indexes corresponding to numbers which are divisible by j as they are non-primes.
}
}
}
for(lli i=2;i<=n;i++)
{
if(stat[i]==0)//Finally finding which are still unmarked as the are not divisible by any number (except divisible by 1 and the number itself as prime number's definition) and the numbers corresponding to these indexes are primes.
{
prime.push_back(i);//storing primes, as index i is unmarked so i is a prime.
}
}
}
int main()
{
cout<<"Enter upto which number you want to look for primes: ";
cin>>upto;
sieve(upto);
for(int i=0,z=prime.size();i<z;i++)//printing
{
cout<<prime[i]<<" ";
}
cout<<endl;
}