我需要一种方法来返回数组中的素数。
所以如果给出: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++; // <--- 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;
}
这就是我用来测试代码的原因:
int[] num = primeArray(11);
System.out.println(num[0]);
System.out.println(num[1]);
但是对于输出我得到了这个:
1
2
但是,如果我评论出iP ++; if if语句最终决定只在素数作为参数传递时才执行:isPrime(j)但是如果失败了primeArray方法的全部目的,因为我需要primeArray方法返回一个素数数组。
答案 0 :(得分:10)
您的isPrime()
方法有问题。您需要为false
返回number < 2
。此外,您不需要迭代直到 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;
}
现在,考虑到你的真正问题(注意你的方法很好。如果你改变了你的isPrime()
方法,它会返回正确的结果),但你可以避免迭代两次使用ArrayList
代替数组:
List<Integer> primes = new ArrayList<Integer>();
//loop to find total prime numbers
for (int j = 1; j <= numFind; j ++)
{
if (isPrime(j))
primes.add(j);
}
然后您可以返回 primes ,并将方法的返回类型更改为List<Integer>
而不是int[]
。
public static List<Integer> primeNumberList(int numFind)
如果您确实想要返回int[]
,那么您需要做一些工作,将ArrayList
转换为int
数组。我把这个任务留给你了。只在SO上搜索这个,你会得到太多帖子。
此外,如果您要生成所有素数,直到非常大的数字,那么您应该看看Sieve of Eratosthenes
答案 1 :(得分:0)
您只需输出第一个数组值......
只需更换输出
for(int i = 0; i < num.length; i++)
{
System.out.println(num[i]);
}
您的代码运行正常。
答案 2 :(得分:0)
在isPrime()
方法中,在最后添加一条语句
if(n < 2) return false;
我认为按照目前的方式,当1通过时,你会得到一个真实的。
我能想到的另一个建议是,如果您希望自己的限制很小,可以使用静态表格来获取一些数字。
static int[] PRIME_TABLE = {2,3,5,7,11,13,17,19,23,29,31};
等
因此,当此示例中的限制小于32时,您不需要计算其下面的所有素数,只需遍历此表并返回数字。
答案 3 :(得分:0)
我尝试以不同的方式编写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;
}
答案 4 :(得分:0)
此代码返回小于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;
}
答案 5 :(得分:0)
有几种获取素数数组的方法,最简单的计算方法是使用 Eratatothenes筛子。这会遍历每个递增的数字,在找到下一个质数时,所有此后的倍数都标记为非质数。大多数实现都使用如下所示的布尔数组:
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;
}
从罗希特·贾因(Rohit Jain)建议的更正实现开始(如上所述),您可能会发现不必测试小于sqrt(p)
的每个数字。如果p
无法被n
整除,那么它就不会被n
的倍数整除-这样,我们只需要测试p
以下的每个素数。例如;因为7不能被2整除,所以也不会被4整除。
这里的问题是,我们现在需要找出小于sqrt(p)
的数字作为质数来检验p。啊,但是不,我们不!我们可以查看我们已知的素数的缓存列表,稍后将以其他方法返回。在缓存已知素数的列表时,也不需要在其他方法中创建新列表,我们只需返回缓存(一旦生成)即可!成品看起来像这样:
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;
}
}
现在您可以使用Primes.isPrime(...)
来检查;)
答案 6 :(得分:0)
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;
}
}
答案 7 :(得分:0)
您可以通过使用Sieve算法查找素数来进一步优化它。执行以下步骤可以找到最高达(10 ^ 9)-1的素数。
#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;
}