Store prime numbers into partial array - java

I'm trying to store all the prime numbers 1-100 into a partial array, and then print the result.
I need to have them in separate methods.
I think I figured out how to tell if a number is prime, but not how to return that number back to the main method to be store into an array.
Here's my code so far:
Main method:
public static void main (String[] args) throws IOException {
int[] primeArray = new int[25];
primeArray[0] =2;
int numPrimes = 1;
boolean prime;
int currNumber;
for(currNumber=3; currNumber<=100; currNumber++) {
prime= isPrime(currNumber,primeArray,numPrimes);
if(prime=true) {
primeArray[numPrimes]=currNumber;
numPrimes++;
if (numPrimes==25)
break;
}
System.out.println(primeArray[numPrimes]);
}
}
isPrime method:
public static boolean isPrime (int currNum, int [] primeArray,int numPrimes) {
boolean prime=true;
for(int i=0; i<numPrimes; i++) {
if(currNumber/2%primeArray[i]==0)
prime=false;
break;
}
return prime;
} // end isPrime
Any advice would be appreciated; super confused right now.

You are doing a pretty good job, I can see a couple of errors right away:
if(prime=true) should be if(prime==true) or for booleans you normally use only the expression, i.e. if(prime)
Check the loop where you check for primehood. x % 1 will always be 0 ;)

A few things wrong with your code. In the main method, you are passing currNum in to the isPrime() method call. That variable doesn't exist, your code shouldn't compile. You want to pass currNumber into that method call. The second thing is your if statement is assigning the "prime" boolean to true, not checking it. It should just be if(prime).
In your isPrime() method, you can add a break; in the prime check because if it's divisible by a number, it's not prime, no need to check the rest of the divisors:
if(currNum%primeArray[i]==0) {
prime = false;
break;
}
Since you are iterating through the prime array, the for loop should stop at the number of primes, not the current number:
for(int i=0; i<numPrimes; i++)

I would change the isPrime signature as public static boolean isPrime(int number) and define it such that it would take a number and return true/false based on whether the number is prime or not.
public static boolean isPrime(int number) {
if(number < 2) {
return false;
} else if(number < 4) {
return true;
}
for(int i=2; i<=number/2; i++) {
if(number % i == 0) {
return false;
}
}
return true;
}

Related

Getting weird output while finding prime number in java

I have two methods to find out prime number in java method - 2 working fine but getting wrong output from method one, can any help me where i did wrong in logic. Thanks in advance
My entire code
package prepare;
import java.util.Scanner;
public class Squar {
//Method - 1 to find prime number
boolean isPrime(int num){
int exp = (int)Math.sqrt(num);
for(int i=2;i<exp;i++){
if(exp%2==0){
return false;
}
}return true;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
Squar s = new Squar();
System.out.println("From M1 "+s.isPrime(num));
scan.close();
System.out.println("From M2 "+s.isPrimeNumber(num));
}
//Method - 2 to find prime number
public boolean isPrimeNumber(int number) {
if(number == 1){
return false;
}
if (number == 2 || number == 3) {
return true;
}
if (number % 2 == 0) {
return false;
}
int sqrt = (int) Math.sqrt(number) + 1;
for (int i = 3; i < sqrt; i += 2) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
for input : 63 actual out put would be false in prime number but getting
different output from method one
output
63
From M1 true
From M2 false
In isPrime() method, Shouldn't you be checking num % i == 0 rather than exp % 2 == 0?
Change isPrime function like this.
boolean isPrime(int num) {
int exp = (int) Math.sqrt(num);
for (int i = 2; i < exp; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
Because in if condition you are checking exp%2 == 0 . But this statement does not change when iterating on i < exp. So this logic should be on with num % i == 0
Have a look at this line of your code
if(exp%2==0){
it should be num % i
Well I think the culprit is
if(exp%2==0){
and it is causing a problem while iterating i<exp.So you may want to tweak it to
num%i==0
I have tried to give a few other approaches to this issue.
I hope that would be helpful.
I think there is a reason that tempted you to use
(int)Math.sqrt(num);
I have tried to elaborate it below.
Consider below 3 approaches.
All of them are correct but the first 2 approaches have some drawbacks.
Approach 1
boolean isPrime(int num) {
for(int i=2;i<num;i++) {
if(num%i==0)
return false;
}
return true;
}
We have a scope to make it faster.
Consider that if 2 divides some integer n, then (n/2) divides n as well.
This tells us we don't have to try out all integers from 2 to n.
Now we can modify our algorithm:
Approach 2
//checks whether an int is prime or not.
boolean isPrime(int num) {
for(int i=2;2*i<num;i++) {
if(num%i==0)
return false;
}
return true;
}
Finally, we know 2 is the "oddest" prime - it happens to be the only even prime number.
Because of this, we need only check 2 separately, then traverse odd numbers up to the square root of n.
I think this might have tempted you to use (int)Math.sqrt(num);
Approach 3
//checks whether an int is prime or not.
boolean isPrime(int num) {
//check if num is a multiple of 2
if (num%2==0) return false;
//if not, then just check the odds
for(int i=3;i*i<=num;i+=2) {
if(num%i==0)
return false;
}
return true;
}
Hence, we've gone from checking every integer (up to n to find out that a number is prime) to just checking half of the integers up
to the square root.
Is it not an improvement, especially considering when numbers are large.
Well, your first algorithm is almost (replace %2 with %i) correct. I do not know the second algorithm, but i would definitely change it to this form:
public boolean isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i < Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}

Why does it matter if I declare a boolean outside vs. inside this while loop?

public class FindPrimes {
public static void main(String[] args) {
int Number_of_prime = 50;
int number_of_final = 10;
int count = 0;
int number = 2;
boolean isPrime = true;
while (count < Number_of_prime) {
for (int divisor = 2; divisor <= number / 2; divisor++) {
if (number % divisor == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
count++;
if (count % number_of_final == 0)
System.out.println(number);
else
System.out.print(number + " ");
}
number++;
}
}
}
The program should find the first 50 prime numbers. When I declare boolean isPrime outside of the while loop (example above) I only get the primes 2 and 3, but when I declare boolean isPrime inside the while loop, I get all 50 prime numbers.
Why is this happening?
I am assuming that you're getting the right answer but you're not sure how/why it is.
Declaring isPrime outside of while does not work. Why? Because if you don't find a prime number within the loop, you set isPrime to false ...and you never reset it back to true ever again. Therefore, any subsequent numbers that come after the non-prime number would automatically default to a non-prime number.
Declaring isPrime inside of while works. Why? Because everytime you find a prime OR non-prime number, you will reset isPrime back to its original value and every subsequent number can and will be evaluated for its prime-ness accordingly.
Try drawing it out if you still have trouble understanding.
Hope that helps.

Prime Sieve only prints integers 1-3

Recently, I've been attempting to create a program that prints prime numbers until a user-specified integer is achieved, the program itself including a "PrimeCheck" class, a "PrimeSieve" class of sorts, and a "Main" class:
public class PrimeCheck {
boolean result;
public PrimeCheck() {
result = true;
}
public boolean primeCheck (int num) {
int i, num1 = num - 1;
for (i = num1; i > 1; i--) {
if (num % i == 0) {
result = false;
}
}
return result;
}
}
import java.util.ArrayList;
public class PrimeSieve {
public PrimeSieve() {
}
PrimeCheck PCObj = new PrimeCheck();
ArrayList<Integer> primes = new ArrayList<Integer>();
public void primeSieve(int num) {
int[] arr = new int[num];
for (int i = 0; i < num; i++) {
arr[i] = i + 1;
if (PCObj.primeCheck(arr[i]) == true) {
primes.add(arr[i]);
}
}
for (int c = 0; c < primes.size(); c++) {
System.out.print(primes.get(c) + " ");
}
}
}
import java.util.Scanner;
public class PrimeSieveMain {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
PrimeSieve PSObj = new PrimeSieve();
System.out.println("Prime Sieve");
System.out.print("Limit: ");
int limit = input.nextInt();
PSObj.primeSieve(limit);
}
}
Pardon my inexperience, yet I cannot seem to locate the problem in this program.
Your problem is in the PrimeCheck class. That class has a state variable (a field) named result. State variables retain the value between calls, for as long as the object is "alive".
So as soon as you hit a number that is not prime, you set this result to false. That value is kept and never changes.
The result variable should be a local variable, not a state variable, and it should be set to true at the beginning of the method. This way it will start fresh every time.
Other notes:
There is really no point in the PrimeCheck class. It doesn't represent a real "entity", and the method can easily be added to the PrimeSieve class. Creating classes for different entities is a good practice, but I think in this case there is no point - it just has one function and that function doesn't depend on anything but its parameters.
If you meant to represent the Sieve of Eratosthenes then this is not the correct algorithm. This is the naive algorithm - it just tests each number individually and doesn't cross out multiples of previous primes as the real Sieve does.
The PrimeCheck has serveral design problems, the first is you designed the result variable as a member, and its only initialized to true upon construction, but updated with false in primeCheck(). Once it has returned false, it will return false on all subsequent calls.
Its also not necessary to design the result as a member, since the result is only related to the method primeCheck(), thus change it to return the value directly, eliminating the member:
public class PrimeCheck {
public boolean primeCheck (int num) {
for (int i = num - 1; i > 1; i--) {
if (num % i == 0) {
return false;
}
}
return true;
}
}
Since PrimeCheck now has no state left, the method could also be made static, making the PrimeCheck instance in your program superflous. You could just call the static method.
PrimeCheck is also terribly inefficient, due to several design choices - one is you start testing from (num - 1), but the most common divisors are the smallest numbers. So it would be more efficient to start testing from the lower end and work the loop upwards. The upper bound (num - 1) is also chosen poorly. The possible largest divisor for num is the square root of num, so the upper bound should be that.
When you get the number is not a prime:
public boolean primeCheck (int num) {
int i, num1 = num - 1;
for (i = num1; i > 1; i--) {
if (num % i == 0) {
result = false;
}
}
return result;
}
result become false, and never change, so I suggest this:
public boolean primeCheck (int num) {
result=true;
int i, num1 = num - 1;
for (i = num1; i > 1; i--) {
if (num % i == 0) {
result = false;
}
}
return result;
}
Before you start to determine prime, you should presume it is a prime
Not tested, just an idea

Prime Number Program Problems

I'm currently working on a program in which the user inputs a number, and the program will give you the number of prime numbers up to that number. Although there are no errors, the program always outputs the same number: 3. This is the code:
public static int Prime(int num){
boolean isPrime = true;
int count = 0;
for (int a = 2; a <=num; a++){
for (int i = 2; i <= a/2; i++){
if (a == 2 || a == 3 || a == 5){
isPrime = true;
}
else if (a % i == 0){
isPrime = false;
}
}
if (isPrime == true)
count++;
}
return count;
}
In your inner for loop, you are setting isPrime, but then you keep looping. Subsequent loops may set isPrime to false if a candidate divisor i doesn't divide cleanly. Only 2, 3, and 5, the 3 numbers in your first if condition, set it to true always, so you always get 3.
Instead, set isPrime to true at the beginning of the inner for loop, and break out of the inner for loop after each time you set isPrime. If the number is 2, 3, or 5, set to true and break so nothing can set it to false, so you can count it. If you found a factor, it's not prime, so set to false and break so nothing can set it to true and it's not counted.
Incidentally, your final if condition tests a boolean; it can be simplified to if (isPrime).
Your strategy is to test each number from 2 through num for primality by scanning for factors other than itself and 1. That's ok, albeit a bit simplisitic, but your implementation is seriously broken.
An approach involving scanning for factors implies that you start by guessing that the number being tested is prime, and then go looking for evidence that it isn't. You've missed the "guessing it's prime" part, which in your particular code would take the form of setting isPrime to true at the beginning of your outer loop.
Your code, on the other hand, never resets isPrime to true after testing the case of a == 5. That variable will be set to false when testing the case of a == 6, and will remain so for the duration. That is why you always get the result 3 for any input greater than 4.
If you properly reset isPrime in the outer loop then you can also remove the first part of the conditional in the inner loop, as it will be redundant. It is anyway never executed in the cases of a == 2 and a == 3 because the inner loop performs zero iterations in those cases.
Note also that it would be more efficient to break from the inner loop as soon as you determine that a is composite, and that you run more iterations of that loop than you need to do for primes (it would be sufficient to loop until i exceeds the square root of a; that is, until i * i > a).
Finally, note that this problem would be more efficiently implemented via the Seive of Eratosthenes (or one of the other prime number seives) as long as the numbers you want to test are not so large that the needed array would be prohibitively large.
I simplified your code by reducing number of operations which is needed to check if a is 2, 3, or 5.
public static int Prime(int num) {
int count = 0;
if (num >= 2) {
count++; // One optimization here
}
for (int a = 3; a <= num; a+=2) { // Another one here as we don't have any even number except 2 :D
boolean isPrime = true;
for (int i = 2; i <= a / 2; i++) {
if (a % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
count++;
}
}
return count;
}
#include <iostream>
using namespace std;
int numberOfPrimes(int num)
{
if(num==2)
return 1;
else if(num<2)
return 0;
int prime=1;
for(int i=3;i<=num;i++)
{
for(int j=2;j<=(i/2)+1;j++)
{
if(i%j==0)
break;
if(j==(i/2)+1)
prime++;
}
}
return prime;
}
package com.amit.primenumber;
public class PrimeNumber {
public static void main(String[] args) {
long number=23L;
String message=null;
PrimeNumber primeNumber = new PrimeNumber();
boolean result = primeNumber.primeNumber(number);
if(result){
message="a Prime Number";
}else{
message="Not a Prime Number";
}
System.out.println("The given "+number+" number is "+message);
}
public boolean primeNumber(long number){
for(long i=2;i<=number/2;i++){
if(number%i==0){
return false;
}
}
return true;
}
}
package basics;
public class CheckPrimeOrNot {
public void checkprimeNumber(int i){
int flag=0;
if(i>2){
for(int j = 2; j <= i/2; j++){
if(i%j == 0){
System.out.println("Given number is Not Prime");
flag=1;
break;
}
}
if(flag==0){
System.out.println("Given number is Prime");
}
} else{
System.out.println("Please enter a valid number");
}
}
public static void main(String[] args) {
CheckPrimeOrNot CheckNumber = new CheckPrimeOrNot();
CheckNumber.checkprimeNumber(11);
CheckNumber.checkprimeNumber(0);
CheckNumber.checkprimeNumber(250365);
CheckNumber.checkprimeNumber(1231);
}
}

How do I return these using only one method?

public class newClass {
public static void main(String[] args)
{
int nullValue=0;
int nullValue2=1;
int nullValue3=0;
int nullValue4=0;
int [] sourceArray = {4,5,6,7};
int [] targetArray = new int [4];
for (int i=0; i<sourceArray.length; i++)
{
nullValue+=sourceArray[i];
}
targetArray[0]=nullValue;
// I added all sourceArray elements together and passed it to targetArray[0]
for (int i=0; i<sourceArray.length; i++)
{
nullValue2*=sourceArray[i];
}
targetArray[1]=nullValue2;
// I multiplied all sourceArray elements together and assigned the result to targetArray[1]
for (int i=0; i<sourceArray.length; i++)
{
nullValue3 += getResult(sourceArray[i]);
}
targetArray[2]=nullValue3;
// I tried to add all odd numbers in sourceArray together and assign it to targetArray[2]
for (int i=0; i<sourceArray.length; i++)
{
nullValue4 += getResult(sourceArray[i]);
}
targetArray[3]=nullValue4;
// Same as previous except I need to do that with even numbers.
}
public static int getResult (int x)
{
if (x%2 == 0)
{
return x;
}
else
{
return 0;
}
}
}
You can read my comments above. I realize I can create another method for the last part but I am supposed to use only one method to return odds and evens. I tried almost anything. I can't think of any other ways anymore. Obviously I can't return x in both cases(Yeah I was too desperate to try that).
Straight to the point. I need one method to return x if it's odd or if it's even(We can say it's impossible by the look of that sentence already). I guess that's impossible to do with only one method. I'm not good at java yet so I'm not sure. Maybe there are other ways to do that with only one method which may be so easy. I worked on it for like 6 hours so I'm asking you guys. Thanks.
Create a method to return a boolean if the number is even like so
public static boolean isEven(int x)
{
return (x%2 == 0)
}
Then in your loop for evens
for (int i=0; i<sourceArray.length; i++)
{
if(isEven(x))
nullValue3 += sourceArray[i];
}
For odds just change to if(!isEven(x))
But this is probably deviating from the requirements as you probably want a method that returns an int and you could just put the condition directly in the loop and not need a method
If I understand your question correctly, what you want is to be able to tell the getResult function whether to give you only odd numbers or only even numbers. Without getting complicated, this is what I would do:
public static int getResult(int x, boolean evens) {
if (x % 2 == 0) {
return evens ? x : 0; // shorthand for: if(evens) {return x;} else {return 0;}
} else {
return evens ? 0 : x;
}
}
Simply speaking, I pass a flag value (evens) to the getResult function. This flag tells me whether to filter for even numbers or for odd numbers.
I test whether x is even (x % 2 == 0). If it is, I return it if I'm looking for evens, and I return 0 if I'm looking for odds. If x wasn't even, then I do the opposite.
It would be a little cleaner to write a pair of helper functions, which you could then call from your getResult function.
private static int getIfEven(x) {
if (x % 2 == 0) {
return x;
}
return 0;
}
private static int getIfOdd(x) {
if (x % 2 == 0) {
return 0;
}
return x;
}
public static int getResult(int x, boolean evens) {
// shorthand for:
// if (evens) {
// return getIfEven(x);
// } else {
// return getIfOdd(x);
// }
return evens ? getIfEven(x) : getIfOdd(x);
}
Depending on how much you're allowed to deviate from the current setup (I assume this is homework), you could also just write an isEven(int x) function and call that at each step through the loop, only adding the number if it is/isn't even.

Categories

Resources