Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
This code is meant to find the 1001st prime but gives me the answer 47 which is clearly wrong.
public class problem7 {
public static void main(String[] args) {
int[] myarray = new int[1001];
int j = 0;
boolean prime = false;
for (int i = 2;; i++) {
for (int k = 2; k < i; k++) {
if (i == (k - 1) && i % k != 0) {
prime = true;
}
if (i % k == 0) {
prime = false;
prime = true;
}
if (prime) {
myarray[j] = i;
}
if (j == 1000) {
System.out.println(myarray[1000]);
return;
}
j++;
}
}
}
}
Any help would be greatly appreciated.
Your check for prime is wrong: you cannot declare a number prime and set prime = true based on a single test. The inner loop should set prime to false, but it shouldn't reset it to true: once it's false, it's false.
The algorithm should proceed as follows:
For each i, set prime=true
Loop over potential divisors k
If a divisor such that i % k == 0 is found, set prime = false, and break the loop
If prime is still true at the end of the nested loop, add i to the list of primes.
This should give you a correct result, at which point you should consider optimizing your solution using considerations below:
If you did not find a divisor among k below or at sqrt(i), then i is prime
You do not have to try all numbers k, only the ones from the list of primes that you have discovered so far.
I think j++ is increment only if prime number is inserted not at all case.By using this code you will be get your 1001 Prime number
public static void main(String[] args) {
int[] myarray = new int[1001];
int j = 0;
for (int i = 2;; i++) {
boolean prime = false;
for (int k = 2; k < i; k++) {
if (i % k == 0) {
prime = true;
}
}
if (!prime) {
myarray[j] = i;
j++;
}
if (j == 1001) {
break;
}
}
for (int primeNumber : myarray) {
System.out.println(primeNumber);
}
}
This is an implementation of dasblinkenlights algorithm!
public static void main(String args[]) {
int[] primes = new int[1001];
int i = 1;
int index = 0;
while (primes[1000] == 0) {
i++;
boolean skip = false;
for (int i1 : primes) {
if (i1 == 0)
break;
if (i % i1 == 0) { //checks if the number is a multiple of previous primes, if it is then it skips it
skip = true;
break;
}
}
if (!skip) {
if (isPrime(i)) {
primes[index] = i;
System.out.println(i);
index++;
}
}
}
}
static boolean isPrime(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0)
return false;
}
return true;
}
The primality test you done here is kind of ambiguous. Because the general approach is, we pick any number assuming its prime, so at the beginning, prime = true. Then if there exist any factor k of input such that k < input and kthen the number is not prime, so prime = false.
I modified your code and get a result: 104743 .
Update: Here is a bit faster way to find large prime. The inner loop will iterate up to square root of i, reason: Why do we check upto the square root of a prime number to determine if it is prime?
public static void main(String[] args) {
int[] myarray = new int[10001];
int j = 0;
boolean prime = true;
int i = 2;
while (true) {
prime = true;
for (int k = 2; k*k <= i; k ++) {
if (i % k == 0) {
prime = false;
}
}
if (prime) {
myarray[j] = i;
if (j == 10000) {
System.out.println(myarray[10000]);
return;
}
j++;
}
if(i > 4)
i += 2;
else
i++;
}
}
Related
This is my block of code for determining if a number is prime or not which is really a simple problem. however, it does not pass the unit test and I have no idea why. I have tried different primitive variable types, but to no avail. It passes all the explicit test cases, so I have no idea which value of n it is not checking correctly of its prime status.
public static boolean isPrime(int n) {
boolean f = true;
if (n % 2 == 0) {
return false;
}
double sqrt = Math.sqrt(n);
for (int i = 3; i <= sqrt; i++) {
if (((n % i) == 0)) {
f = false;
break;
}
}
return f;
}
The unit test in question gives the result:
java.lang.AssertionError:
Expected :783904569
Actual :3149358104
And here is the unit test code
CRC32 check = new CRC32();
for(int k = 0; k < 10_000_000; k++) {
if(Primes.isPrime(k)) { check.update(k); }
}
assertEquals(783904569L, check.getValue());
}
I have tried everything reasonable including re writing the code differently, but it keeps giving the same answer.
Your isPime() has two mistakes:
isPrime(1) == true
isPrime(2) == false
The test passes if you add the following to the beginning of the method:
if (n == 1) return false;
if (n == 2) return true;
You can speed it up with Sieve of Eratosthenes.
static final int MAX_PRIMES = 10_000_000 + 1;
static final boolean[] PRIMES = new boolean[MAX_PRIMES];
static {
Arrays.fill(PRIMES, true);
PRIMES[0] = PRIMES[1] = false;
for (int i = 2, end = (int)Math.sqrt(MAX_PRIMES); i <= end; ++i)
for (int j = i + i; j < MAX_PRIMES; j += i)
PRIMES[j] = false;
}
public static boolean isPrime(int n) {
return PRIMES[n];
}
My code
void printPrimes (int max) {
boolean prime;
for (int n = 2; n < max; n++){
prime = true;
double maxF;
maxF = Math.sqrt(n);
for (int f = 2; f < maxF; f++) {
if (n % f == 0) {
prime = false;
}
}
if (prime == true) {
System.out.println(n + " is prime");
}
}
}
This the result I get
4 is prime
5 is prime
6 is prime
7 is prime
8 is prime
9 is prime
10 is prime
11 is prime
what do I do to fix this issue
Debug your code. As in, take out a pen, be the computer. You answer, without running this code, what it should do. Then check what it actually does with a debugger (or sysout statements if you must). There where you find a difference, you found a bug.
For example, Math.sqrt(4), what's that? is 2 less than 2?
Change your conditional in your loop
for (int f = 2; f <= maxF; f++) { // should be <= maxf
if (n % f == 0) {
prime = false;
}
}
at least replace f < maxF with f*f <= max
Because loop maximum should be less or equals to
Math.sqrt(number)
public class Main {
public static void main(String[] args) {
printPrimes(20);
}
static void printPrimes (int max) {
for(int i=2;i<=max;i++){
if(isPrime(i)){
System.out.println(i+" is prime");
}
}
}
static boolean isPrime(int number) {
if(number < 2){
return false;
}
for(int i=2;i<=Math.sqrt(number);i++){
if(number % i == 0){
return false;
}
}
return true;
}
}
My code in Java:
import java.util.Scanner;
public class PrimeNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Введите целое число: ");
int n = scanner.nextInt();
boolean isPrime = false;
for (int i = 2; i <= n; i++) {
for (int j = 2; j < i; j++) {
if (i % j == 0) {
isPrime = false;
break;
} else {
isPrime = true;
}
}
if (isPrime) {
System.out.println(i);
}
}
}
}
But my teacher said that I should move the boolean variable into the loop. This will simplify the code.
But I do not understand how to do it.
What your teacher is saying is that this line:
boolean isPrime = false;
Needs to be moved into the loop where the comments are. You are clearly looking for all prime numbers between 2 and n. Your loop variable 'i' is the prime-number to test, and whether it is prime or not, needs to be initialized to false every time you start an iteration test.
for (int i = 2; i <= n; i++) {
// NEEDS TO BE RIGHT HERE -
boolean isPrime = true;
// You are finding Prime Numbers, and the outer-loop (loop-var 'i')
// Means the 'isPrime' needs to be re-initialized each time you start testing
// whether a certain number, i, is prime or not!
for (int j = 2; j < i; j++)
if (i % j == 0) { isPrime = false; break; }
// and this line needs to be removed completely.
// else { isPrime = true; }
if (isPrime) System.out.println(i);
}
in java what i am trying to do is have a user input a value greater than 0 and with that number they input list that amount of prime numbers starting from 2
so if the user inputs "3" the program will display 2,3,5
if the user inputs "5" the program will display 2,3,5,7,11
and so on
the problem is I cant figure out how to have the user input do this correctly, i either end up with the numbers repeating however many times or the list ending at the user input, any help would be apreciated
import java.util.Scanner;
public class Primes
{
public static void main(String[] args)
{
Scanner console = new Scanner(System.in);
int n = console.nextInt();
if(n<=0)
{
return;
}
else
{
for(int i=2; i < 100; i++)
{
boolean isPrime = true;
for(int j=2; j < i; j++)
{
if(i%j == 0)
{
isPrime = false;
break;
}
}
if(isPrime)
{
System.out.println(i);
}
}
}
}
}
Keep a count of how many primes have been found by changing your for loop to stop when you've found enough primes and performing primesFound++ when a prime is found:
for (int i = 2, primesFound = 0; primesFound < n; i++)
{
boolean isPrime = true;
for (int j = 2; j < i; j++)
{
if (i % j == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
System.out.println(i);
primesFound++;
}
}
I rather have code that is refactored, each method is doing one thing, it makes it much easier to read, debug and maintain.
All we need to do is separate the logic that checks if a number is prime from the logic that goes over the numbers until n prime numbers are found:
public static void main(String[] args) {
printNPrimes(5);
}
static private boolean isPrime(int n) {
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
static private void printNPrimes(int n) {
int i = 2;
while (n > 0) {
if (isPrime(i)) {
System.out.println(i + " is Prime");
n--;
}
i++;
}
}
//prime
int i,j;
Set<Integer> primeNums = new HashSet<>();
Set<Integer> notPrimeNums = new HashSet<>();
Stack<Integer> stack = new Stack<>();
for(i=1; i<fiboList.size(); i++) {
for(j=i+1; j<fiboList.size(); j++) {
if( i % j == 0 ) {
notPrimeNums.add(fiboList.get(i));
}else {
primeNums.add(fiboList.get(i));
}
}
}
stack.addAll(primeNums);
Collections.sort(stack);
System.out.println("Prime numbers:"+" "+stack);
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
My program that calculates the sum of primes is very slow for very large nth term. Please how do I optimize the processing time of my program? The fastest program will be appreciated and the reason why mine is slow for large sets of data. Thanks.
Here's the Java program:
public class SumOfPrimes {
public static void main(String[] args) {
primeNumber(2000000);
}
public static void primeNumber(int nth) {
int counter = 0, i = 2;
while(i>=2) {
if(isPrime(i)) {
counter += i;
}
i++;
if(i == nth) {
break;
}
}
System.out.println(counter);
}
public static boolean isPrime(int n) {
boolean prime = true;
int i;
for(i= 2; i < n; i++) {
if (n % i == 0) {
prime = false;
for (int j = 3; j * j < n; j += 2) {
if (n % j == 0) prime = false;
}
}
}
return prime;
}
}
Well, it's unclear why you have an inner for loop in your isPrime. Removing it will save much time.
Besides, once you find that n is not prime, you should return immediately. Either break out of the loop, or just return false.
Another optimization would be not to test all the number until i < n. It's enough to test until i * i <= n.
public static boolean isPrime(int n) {
int i;
for(i = 2; i * i <= n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
Remember primes you have found, and only test them.
Remove the inner loop.
Test 2, 3, then all odds.
Something like...
public boolean isPrime( ArrayList<Long> primes, long n ){
for( Long t : primes ){
if( n % t == 0 ){
return false;
}
if( t * t > n )return true;
}
return true;
}
public void sumOfPrimes()
{
ArrayList<Long> primes = new ArrayList<Long>();
long n;
double count = 0;
for( n = 2; n < 2000000; n++ ){
if( isPrime( primes, n ) ){
primes.add( n );
count += n;
}
}
}
This should be your isPrime function-
bool isPrime (int number) {
if (number < 2) return false;
if (number == 2) return true;
if (number % 2 == 0) return false;
for (int i=3; (i*i) <= number; i+=2) {
if (number % i == 0 ) return false;
}
return true;
}
Putting together all the answers to my question above, my program has been re-written and it is much faster for very large datasets.
public class SumOfPrimes {
public static void main(String[] args) {
primeNumber(2000000);
}
public static void primeNumber(int nth) {
int i = 2;
long counter = 0;
while(i>=2) {
if(isPrime(i)) {
counter += i;
}
i++;
if(i == nth) {
break;
}
}
System.out.println(counter);
}
public static boolean isPrime (int n) {
if (n < 2) return false;
if (n == 2) return true;
if (n % 2 == 0) return false;
for (int i=3; (i*i) <= n; i+=2) {
if (n % i == 0 ) return false;
}
return true;
}
}
#aega's solution for the isPrime function did the trick. Now 2 million datasets can be calculated for less than 2 secs.
We no need to test from 1 to n, even 3 to n/2 or 3 to sqrt(n) is also too much for testing for a bigger number.
To make the testing the least, we can only test n with the previous prime that have been found up to sqrt(n), like what mksteve has mentioned.
static List<Integer> primes = new ArrayList<>();
static boolean isPrime (int number) {
if (number < 2) return false;
if (number == 2) return true;
if (number % 2 == 0) return false;
int limit = (int) Math.sqrt(number);
for (i : primes) {
if (i > limit) break;
if (number % i == 0 ) return false;
}
return true;
}
public static void primeNumber(int nth) {
int i = 2;
long counter = 0;
while(i <= nth) {
if(isPrime(i)) {
counter += i;
primes.add(i);
}
i++;
}
System.out.println(counter);
}
A faster program will be to store the generated prime numbers in an array and use only those elements for divisibility check. The number of iterations will reduce dramatically. An element of self-learning is there in this.
I don't have time right now. But, when I'm free, will write a java code to implement this.
Use the power of Lambda for dynamic functional referencing and streams for optimized performance with inbuilt filter conditions.
public static boolean isPrime(final int number) {
return IntStream.range(2,(long) Math.ceil(Math.sqrt(number + 1))).noneMatch(x -> number % x == 0);
}