isItPrime using a boolean method? So Close - java

I feel I am so close! The output is just outputting true true true or false false false (depending on the length of the array and the user inputs.
I feel this is because of the if/else! For instance, if the number you input first is either true or false it makes all of them that!?
This is supposed to print to the console the numbers in the array, the index of the array numbers, and whether they are prime or not, individually.
Thanks for the help!!
import java.util.Scanner;
import java.util.Arrays;
public class isItPrime {
//main method
public static void main (String[] args) {
//Scanner
Scanner input = new Scanner(System.in);
System.out.println("Enter length of array: ");
int n = input.nextInt();
int[] numbers = new int[n];
System.out.println("Enter " + n +" integers to fill the array: ");
for(int i=0; i<n; i++){
numbers[i] = input.nextInt();
}
System.out.println(Arrays.toString(numbers));
for(int j=0; j<n; j++){
System.out.println(numbers[j] + ": " + j + " -- " + isPrime(numbers));
}
}
public static boolean isPrime(int[] numbers){
boolean Prime = true; //initial boolean value
for (int i = 2; i<numbers.length; i++) {
for (int j=0; j<numbers.length; j++) {
if (numbers[j] == 1 || numbers[j] == 0) {
Prime = false;
}
else if (numbers[j]%i==0){ //function which determines if an int is prime.
Prime = false;
}
else {
Prime = true;
}
}
}
return Prime;
}
}

This is what you need:
public class IsItPrime{
//main method
public static void main(String[] args) {
//Scanner
Scanner input = new Scanner(System.in);
System.out.println("Enter length of array: ");
int n = input.nextInt();
int[] numbers = new int[n];
System.out.println("Enter " + n + " integers to fill the array: ");
for (int i = 0; i < n; i++) {
numbers[i] = input.nextInt();
}
System.out.println(Arrays.toString(numbers));
for (int j = 0; j < n; j++) {
System.out.println(numbers[j] + ": " + j + " -- " + isPrime(numbers[j]));
}
}
public static boolean isPrime(int numbers) {
boolean Prime = true;
if (numbers == 1 || numbers == 0) {
Prime = false;
return Prime;
}
for (int i = 2; i < numbers; i++) {
if (numbers % i == 0) {
Prime = false;
return Prime;
} else {
Prime = true;
}
}
return Prime;
}
}
Only a single integer needs to be passed to the isPrime function.
Also, for processing this integer only a single loop would suffice in the isPrime function.
I have made the required changes.

Assuming you want to return which elements are prime:
public static boolean isPrime(int[] numbers){
boolean prime[] = new boolean[numbers.length]; //initial boolean value
for (int i = 0; i<numbers.length; i++) {
for (int j=2; j<=sqrt(numbers[i]); j++) {
if (numbers[j]%i==0){ //function which determines if an int is prime.
prime[i] = false;
continue;
}
}
prime[i] = true
}
return prime;
}
I'm creating a prime array and whichever is prime, I'm making its position in the array true, and i continue with the next element.
Also, for prime, you have to check until square root of the number for the sake of efficiency.
For example, if you want to check if 10 is prime, it is better to iterate until sqrt(10)=3.2.

Your biggest problem is your isPrime() method should calculate if a particular number is prime, not analyse an array of numbers.
Try this:
public static boolean isPrime(int number){
// return true if prime
}
And call it like this:
System.out.println(numbers[j] + ": " + j + " -- " + isPrime(number[j]));

Altered method to return string i.e, "Prime" or "Not Prime".
public static String isPrime(int numbers) {
if (numbers == 1 || numbers == 0) {
return "Not Prime";
}
for (int i = 2; i < numbers; i++) {
if (numbers % i == 0) {
return "Not Prime";
}
}
return "Prime";
}

Related

Prime number check java

Write a program to read n numbers. The first number specified as input will be n. Next, the program should read n integer numbers.
The program should check for each number if it is prime as well as if its reverse is prime.
Display all such numbers in ascending order.
Consider below example for input and output:
Input:
7
11
12
23
19
7
113
101
Output:
7
11
101
113
My code
public class Prime {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int temp;
int[] a = new int [x];
int[] r = new int [x];
int[]c = new int[a.length+r.length];
int[] rev = new int [x];
for(int i=0;i<x;i++){
a[i] = sc.nextInt();
rev[i]=a[i];
}
for(int i = 0; i < a.length; i++) {
while(rev[i] != 0) {
r[i] = r[i] * 10;
r[i] = r[i] + rev[i]%10;
rev[i] = rev[i]/10;
}
}
for(int i = 0; i < a.length; i++) {
boolean isPrime = true;
for (int j = 2; j < i; j++) {
if((a[i]%j==0) || (r[i]%j==0)) {
isPrime = false;
break;
}
}
if(isPrime)
System.out.println(a[i]);
System.out.println(r[i]);
}
}
}
Somewhere I am stuck I don't know how to eliminate repeated no, how to merge the array at last and also it is printing 1 and 2 as prime no when I give input and 2
You need to use TreeSet - which will contain only distinct elements and give result in sorted form. You can refer to following code-
Set<Integer> set = new TreeSet<>();
for(int i = 0; i < a.length; i++) {
boolean isPrime = true;
if(isPrime(a[i]) && isPrime(r[i]))
set.add(a[i]);
}
Iterator it = set.iterator();
while(it.hasNext())
System.out.print(it.next() + " ");
Also create a function for checking prime numbers -
private static boolean isPrime(int num) {
if(num==1) return false;
for(int i = 2; i <= num/2; ++i)
{
if(num % i == 0)
{
return false;
}
}
return true;
}
You can try below code. Hope it helps you,
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class PrimeNumberTest {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>(Arrays.asList(7, 11, 12, 23, 19, 7 ,113, 101));
//To remove duplicates
Set<Integer> set = new TreeSet<>(list);
System.out.println(getPrimeNumbers(set).toString().replaceAll(",", "").replace("]", "").replace("[", ""));
}
//Method to get unique ordered set of prime numbers
private static Set<Integer> getPrimeNumbers(Set<Integer> set) {
Set<Integer> resultList=new TreeSet<>();
set.forEach(ele->{
//check for prime
if(isPrime(ele)){
//if prime number check for reverse and if true, add to result
if(isPrime(reverserNumb(ele)))
resultList.add(ele);
}
});
return resultList;
}
private static boolean isPrime(int num){
if(num<2)
return false;
// Check for even numbers
if (num % 2 == 0) {
return num == 2;
}
// Check for odd numbers
for (int i = 3; i*i <= num; i += 2) {
if (num % i == 0) {
return false;
}
}
return true;
}
private static int reverserNumb(int num) {
return Integer.valueOf(new StringBuilder(String.valueOf(num)).reverse().toString());
}
}
Here is the code for prime test using √n approach
static boolean isPrime(int n){
//corner case
if (n <= 1) return false;
if (n <= 3) return true;
//middle 5 number
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
Use can use set for remove duplicate element
Try if this code works, hope it helps
Code:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class PrimeNumbers {
static ArrayList<Integer> prime = new ArrayList<>();
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
System.out.print("Enter Number of Integers: ");
int number_count = user_input.nextInt();
int[] numbers = new int[number_count];
for (int i = 0; i < numbers.length; i++) {
System.out.print("Enter Integer: ");
numbers[i] = user_input.nextInt();
}
System.out.print("Values Entered: ");
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
checkPrime(numbers[i],false); //false don't reverse
checkPrime(numbers[i],true); //true reverse value to check if it is also prime
}
System.out.print("\nList of prime numbers: ");
Collections.sort(prime);
for(int n : prime){
System.out.print(n + " ");
}
if(prime.isEmpty()){
System.out.print("no prime numbers on list\n");
}
}
//check for duplicates
static void insertValueToPrime(int n){
for(int p : prime){
if(n == p){
return;
}
}
prime.add(n);
}
static void checkPrime(int n,boolean isReverse) {
int i, m = 0, flag = 0,realn = n;
if(isReverse){
n = reverseNumber(n);
}
m = n / 2;
if (n == 0 || n == 1) {
//no a prime number
} else {
for (i = 2; i <= m; i++) {
if (n % i == 0) {
// not a prime number
flag = 1;
break;
}
}
if (flag == 0) {
insertValueToPrime(realn);
}
}
}
static int reverseNumber(int n){
String reverse = "",str=""+n;
for(int i = str.length() - 1; i >= 0; i--)
{
reverse = reverse + str.charAt(i);
}
return Integer.parseInt(reverse);
}
}

I am trying to make a program which will take a number and display the prime number before and after it

I am trying to make a program which will take user input as an integer and will display the prime number before it and after it. I cannot see what I have done wrong as the output is nothing. It would be great if somebody could help!
package prime;
import java.util.Scanner;
public class Prime
{
boolean flag = false;
public boolean isPrime(int x)
{
for (int i = 2; i <= x/2; i++)
{
if (x % i == 0)
{
flag = true;
return flag;
}
}
}
public static void main(String [] abc)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter an number. A prime number preceeding and succeeding that number will be displayed.");
int num = sc.nextInt();
Prime p = new Prime();
for (int j = num;j < num && j > 0;j--)
{
if (p.isPrime(j-1) == true)
{
System.out.println("Prime number predeceeding " + num + " : " + j);
break;
}
}
for (int j = num;j > num;j++)
{
if (p.isPrime(j+1) == false)
{
System.out.println("Prime number succeeding " + num + " : " + j);
break;
}
}
}
}
Here is a modified working code.
Made some changes:-
1.Initialized flag to true and if we find any factor just return false.
2.For finding a greater prime number just start an infinite loop from num+1. But do make sure that the input number is within the Integer value bound i.e 65535.
import java.util.Scanner;
public class Prime
{
boolean flag = true;
public boolean isPrime(int x)
{
for (int i = 2; i < x/2; i++)
{
if (x % i == 0)
{
return false;
}
}
return flag;
}
public static void main(String [] abc)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter an number. A prime number preceeding and succeeding that number will be displayed.");
int num = sc.nextInt();
Prime p = new Prime();
for (int j = num-1; j > 0; j--)
{
if (p.isPrime(j))
{
System.out.println("Prime number predeceeding " + num + " : " + j);
break;
}
}
for(int j=num+1; ;j++)
{
if (p.isPrime(j))
{
System.out.println("Prime number succeeding " + num + " : " + j);
break;
}
}
}
}
Hope this helps!
Your condition on both the for loops will evaluate to false. In the first case:
for (int j = num;j < num && j > 0;j--)
// for(initialization; test-condition; updation)
The test condition is false in the first iteration because you have initialized j to num and you are now checking if j < num which is false. Hence, it never goes into this loop.
Similarly, in the second case:
for (int j = num;j > num;j++)
you have initialized j to num and are now checking if j > num which is obviously false. Hence, the content of this loop is also never executed.
You can correct these by changing the initialization part in both the for loops (as suggested by #zenwraight):
for(int j = num-1; j > 0; j--) // first case
for(int j = num+1; ; j++) // second case

java unable to find the error to print a prime number

This program gets 4 input from the user and prints out all the pairs except for the duplicate pairs. I wanted it print only the pairs that sum equals a prime number. I did the entire program there is no compilation error but in the output it prints to all pairs except the duplicate pair(i want it to print only the pair whose sum= a prime number) can anyone tell me what i am doing wrong
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Prime {
public static List<Integer> numbers = new ArrayList<>(); // a list of integers that was accepted, can be acced in the order they were added
public static Scanner input = new Scanner(System.in);
public static void main(String args[])
{
int inputs = 4;
input(inputs);
for(int i = 0; i < inputs; i++){
for(int j = 0+i; j < inputs; j++){
if(i != j)
System.out.println(numbers.get(i)+ " + " + numbers.get(j) + " = "+ isPrime(numbers.get(i) + numbers.get(j)));
}
} }
public static int isPrime (int sumPair)
{
boolean primeVal =true ;
if(sumPair < 2)
primeVal= false;
else if(sumPair ==2)
primeVal=true;
else if (sumPair % 2 == 0)
primeVal = false;
else
{
int stop = (int)Math.sqrt(sumPair);
for (int d = 3; d <= stop && primeVal; d = d + 2)
{
if (sumPair % d == 0)
primeVal = false;
}
}
return(sumPair);
}
public static void input(int inputNumbers)
{
while(numbers.size() < inputNumbers){ // while there is more inputs needed
System.out.print("Enter a positive integer: ");
int num = input.nextInt();
if(num > 0) // if the input is valid
numbers.add(num);
else // if the input is not valid
while (num <= 0) { // while the input is not valid
System.out.print("Enter a positive integer: ");
num = input.nextInt(); // get the next int if it wasn't valid
if(num > 0) { // if the input gets valid
numbers.add(num);
}
}
System.out.println("Thank you.");
}
}
public static int sumPair(int num1, int num2)
{
return num1 + num2;
}
}
You go to a lot of trouble to compute a boolean primeVal which tells whether the input be true or false, but you never actually return this value. Try this instead:
public static boolean isPrime (int sumPair) {
boolean primeVal = true;
if (sumPair < 2 || sumPair % 2 == 0) {
primeVal = false;
}
else {
int stop = (int)Math.sqrt(sumPair);
for (int d=3; d <= stop; d += 2) {
if (sumPair % d == 0) {
primeVal = false;
break;
}
}
}
return primeVal;
}
Use this main() method:
public static void main (String args[]) {
int inputs = 4;
input(inputs);
for (int i=0; i < inputs-1; i++) {
for (int j=i+1; j < inputs; j++) {
boolean prime = isPrime(numbers.get(i) + numbers.get(j));
if (prime) {
System.out.println(numbers.get(i) + " + " + numbers.get(j));
}
}
}
}
Your condition to determine if you print the current pair or not is if(i != j), so it will only print if i is different from j (duplicate).
You made a nice isPrime function, you should call it.
You made your isPrime function return an int, and I'm pretty sure it should return a boolean instead. Also, it returns the argument you gave it, so it does virtually nothing except spend time in a potentially expensive operation. Perhaps should it return primeVal instead.
Your code should look like:
for(int i = 0; i < inputs; i++){
for(int j = 0+i; j < inputs; j++){
ni = numbers.get(i);
nj = numbers.get(j);
if(isPrime(ni+nj)){
System.out.println(ni + " + " + nj + " = "+ (ni + nj));
}
}
}
What this does is get the numbers for indexes i and j and store them in ni and nj respectively. Then, it checks it their sum is prime. If it is, then it prints the sum.

How to write a loop to display multiples of primes in Java?

My assignment reads:
Write a program that finds all of the prime numbers between one and some number that you allow the user to input.
Find the prime numbers between 0 and the number the user inputs.
Print these prime numbers, one per line.
After each prime number, add a colon and then print out all the non-prime numbers that were eliminated.
Basically, these non-prime numbers are the multiples of the primes.
For example, the output will look like this:
2: 4 6 8 10 12 14 16 18...
3: 9 15 21 27
I did prime numbers. I can not figure out how to calculate and display multiples? Help, please!
package assignment4;
import java.util.Scanner;
public class Assignment4 { /**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
final int START = 1;
System.out.print("Enter the end number number : ");
int end = s.nextInt();
System.out.println("List of prime numbers between " + START + " and "
+ end);
for (int i = START; i <= end; i++) {
if (isPrime(i)) {
System.out.println(i + ":");
}
}
}
public static 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;}
}
I am assuming that you want to have print the multiples until the end number. You could nest a while loop that multiplies the prime number as follows:
for (int i = START; i <= end; i++) {
if (isPrime(i)) {
System.out.print(i + ": "); //Changed to print so that the multiples are on the same line
int multiple = i * 2;
while (multiple <= end) {
multiple += i;
System.out.print(multiple + ", ");
}
System.out.println("");
}
}
Displaying multiples would be easy if you were sieving using sieve of Erathrosthenes. You create an array of numbers from 2 to n. start with 2, mark non-prime all its multiples: 2 4 6... print them. Choose next prime number (i.e. the number which was not marked unprime) i.e. 3, mark non-prime all its multiples (which haven't been already): 9 15 ... and so on.
Simplest Solution:
boolean[] x = new boolean[N];// x[i] is true when i is not prime
for(int i=2;i<N;i++){
if(!x[i]){
System.out.print(i+" : ");
for(int j=i*i;j<N;j+=i){
if(!x[j])
System.out.print(j+" ");
x[j]=true;
}
System.out.println();
}
}
Please check below answer for your requirement,
package assignment4;
import java.util.*;
import java.lang.*;
import java.io.*;
public class Assignment4
{
public static List<Integer> primeNumbers = new ArrayList<>();
public static String strOtherData[];
public static void main (String[] args) throws java.lang.Exception
{
final int START = 1;
System.out.print("Enter the end number number : ");
int end = s.nextInt();
System.out.println("List of prime numbers between " + START + " and " + end);
for (int i = START; i <= end; i++) {
if (isPrime(i)) {
primeNumbers.add(i);
}
}
strOtherData = new String[primeNumbers.size()];
for (int i = START; i <= end; i++) {
isMultiple(i);
}
int tempCount = 0;
for(Integer currentNumber : primeNumbers)
{
System.out.print(currentNumber + ": \t");
if(strOtherData.length > tempCount)
{
System.out.print(strOtherData[tempCount] + "\n\n");
}
tempCount++;
}
}
public static boolean isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i <= n/2; i++)
{
if (n % i == 0)
{
return false;
}
}
return true;
}
public static void isMultiple(int n)
{
if (n <= 1) {
return;
}
if(isPrime(n))
return;
int count = 0;
for(Integer currentInt : primeNumbers)
{
if(strOtherData[count] != null)
{
strOtherData[count] += "," + n;
}
else
{
strOtherData[count] = "" + n;
}
count++;
}
}
}

find all prime numbers from array

I want to create a program that will ask the user to input 5 integers using array and determine all the prime numbers entered. But I have difficulty with it. What seems to be the problem? I use JCreator for this.
import java.util.Scanner;
public class PrimeNumbers{
public static void main (String[] args){
int[] array = new int [5];
Scanner in = new Scanner (System.in);
System.out.println("Enter the elements of the array: ");
for(int i=0; i<5; i++)
{
array[i] = in.nextInt();
}
//loop through the numbers one by one
for(int i=0; i<array.length; i++){
boolean isPrime = true;
//check to see if the numbers are prime
for (int j=2; j<array[i]; j++){
if(array[i]%j==0){
isPrime = false;
break;
}
}
//print the number
if(isPrime)
System.out.println(array[i] + " are the prime numbers in the array ");
}
}
}
You are checking the loop counters, not the values in the array. Try something like
for (int j=2; j<array[i]; j++){
if(array[I]%j==0){
isPrime = false;
break;
}
I haven't tested this.
UPDATE
To print out the results either print each on as it is found, or, copy the prime numbers into an output array and then print that when you have finished the checks. The details will depend on the language you are using.
Please note, you are not using a very efficient detection algorithm; Google for a better one.
You can check all integer numbers until root of the required number
Pseudo code:
for(i=2; i<sqrt(number);i++){
if(number/i===0){
//not prime number
}
}
Find all prime numbers from the array.
package com.myfirstproject;
public class array_Uni_work {
public static void main(String[] args) {
int[] array = {6,48,47,7 , 98,51,87,99,2,0,1,191,157};
// loop through the numbers one by one
for (int i = 0; i < array.length; i++) {
boolean isPrime = true;
if (array[i] == 1)
isPrime = false;
else {
// check to see if the numbers are prime
for (int j = 2; j <= array[i] / 2; j++) {
if (array[i] % j == 0) {
isPrime = false;
break;
}
}
}
// print the number
if (isPrime){
if (array[i] == 0){}
else {
System.out.print(array[i] + " , ");
}
}}
System.out.println(" Are the prime number in the array ");
}
}
public static void main(String[] args) {
int[] array = new int[5];
Scanner in = new Scanner(System.in);
System.out.println("Enter the elements of the array: ");
for (int i = 0; i < 5; i++) {
array[i] = in.nextInt();
}
// loop through the numbers one by one
for (int i = 0; i < array.length; i++) {
boolean isPrime = true;
if (array[i] == 1)
isPrime = false;
else {
// check to see if the numbers are prime
for (int j = 2; j <= array[i] / 2; j++) {
if (array[i] % j == 0) {
isPrime = false;
break;
}
}
}
// print the number
if (isPrime)
System.out.println(array[i] + " is a prime number in the array ");
}
}
Here is more efficient code finding prime number. We only need to check the odd number up to the square root of N, assume the number is greater than 2.
boolean isPrime(int n) {
//check if n is a multiple of 2
if (n%2==0) return false;
//if not, then just check the odds
for(int i=3;i*i<=n;i+=2) {
if(n%i==0)
return false;
}
return true;
}
This is the simplest form of finding the prime numbers from the given array. We can also use scanner by assigning n instead of an array to check whether if it is a prime or non prime from the given input(commented in program).Hope this helps you..!!
public static void main(String[] arg) {
int a[]= {1,2,3,4,5,6,7,8,9,10}; //int n=0 or n=values
int num =0;
String primeNumbers = "";
for (int i = 0; i <= a.length; i++) /*change a.length to n*/
{
int counter=0;
for(num =i; num>=1; num--)
{
if(i%num==0)
{
counter = counter + 1;
}
}
if (counter ==2)
{
//Appended the Prime number to the String
primeNumbers = primeNumbers + i + " ";
}
}
System.out.println("Prime numbers from given array :");
System.out.println(primeNumbers);
}
}
Since you have asked for 5 number explicitly, the code has hardcoded for 5 numbers
import java.util.Scanner;
public class PracticeTest {
public static void main(String args[]) {
int arr[] = new int[5];
Scanner sc = new Scanner(System.in);
System.out.println("Enter 5 numbers");
for (int i = 0; i < 5; i++) {
arr[i] = sc.nextInt();
}
checkPrimeNumbers(arr);
}
public static void checkPrimeNumbers(int arr[]) {
loop1:
for (int j = 0; j < arr.length; j++) {
loop2:
for (int i = 2; i < arr[j]; i++) {
if (arr[j] % i == 0) {
continue loop1;
}
}
System.out.print(arr[j] + " ");
}
}
}
This is the simplest way to accept 'n' integers and display the prime and non prime numbers present in that array. Without using functions
import java.util.Scanner;
// Author Dot-Coin
public class The_Prime {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the size of the array");
int size=sc.nextInt();
int Primer[]=new int [size];
int Non_Primer[]=new int [size];
int Numbers[]=new int [size];
int counter=0;int j=0,k=0,m=0,n=0;
System.out.println("Enter the numbers ");
for(int i=0;i<size;i++)
Numbers[i]=sc.nextInt();
for(int i=0;i<size;i++)
{
if(Numbers[i]==1||Numbers[i]==0)
{
continue;
}
for(n=1;n<=Numbers[i];n++)
{
if(Numbers[i]%n==0)
counter++;
}
if(counter>2)
{
Non_Primer[k]=Numbers[i];k++;counter=0;continue;
}
if(counter==2)
{
Primer[m]=Numbers[i];m++;counter=0;
}
}
System.out.println("The prime numbers are");
for(k=0;k<Primer.length;k++)
{
if(Primer[k]==0)
{
j++;continue;
}
else
System.out.println(Primer[k]);
}
if(j==Primer.length)
System.out.println("Null");j=0;
System.out.println("The Non prime numbers are ");
for( k=0;k<Non_Primer.length;k++)
{
if(Non_Primer[k]==0)
{
j++;continue;
}
System.out.println(Non_Primer[k]);
}
if(j==Non_Primer.length)
System.out.println("Null");
}}

Categories

Resources