Separate prime numbers from array - java

public class HelloWorld {
public static void main(String []args) {
int [] arr = {2, 5, 9, 6, 7, 13, 24, 42, 8};
int [] arr1 = new int[4];
int [] arr2 = new int[arr.length - arr1.length];
for(int i = 0; i < arr.length; i++) {
for(int j = 2; j <= arr[i]/2; j++) {
if(arr[i] % j == 0) {
System.out.println("Number is not prime " + arr[i]);
break;
}
else {
System.out.println("Number is prime " + arr[i]);
break;
}
}
}
}
}
The program should check an array of numbers and print if the given number is prime. There is something wrong, since the first 2 are not marked as prime. Then I don't know why 9 was taken as a prime number.

There are multiple problems in your code.
Why 2 is not taken as prime.
As explained by others, j <= arr[i]/2 is the culprit. According to this condition, j <= 1 and j == 2. So, the loop does not get executed.
Why 9 is taken as prime.
For the the first time when j == 2 and arr[i] == 9. As, 9%2 != 0, the number is printed as prime.
for(int j = 2; j <= arr[i]/2; j++){
if(arr[i] % j == 0){
System.out.println("Number is not prime " + arr[i]);
break;
}
else {
System.out.println("Number is prime " + arr[i]);
break;
}
}
Advice:
Instead of checking for arr[i]/2, you can use square root of number to check instead.
You can refer the following program if needed:
public class PrimeNumber {
public static void main(String []args){
int [] arr = {2,3,4,5,9,6,7,13,24,42,8,400,101};
int [] arr1 = new int[4];
int [] arr2 = new int[arr.length - arr1.length];
boolean flag = true;
for(int i = 0; i < arr.length; i++){
if(arr[i] == 2 || arr[i] == 3 )
{
System.out.println("Number is prime " + arr[i]);
continue;
}
flag = true;
for(int j = 2; j <= Math.sqrt( arr[i] ); j++){
if(arr[i] % j == 0){
System.out.println("Number is not prime " + arr[i]);
flag = false;
break;
}
}
if ( flag )
{
System.out.println("Number is prime " + arr[i]);
}
}
}
}

for (int j = 2; j <= arr[i] / 2; j++) {
if (arr[i] % j == 0) {
System.out.println("Number is not prime " + arr[i]);
break;
} else {
System.out.println("Number is prime " + arr[i]);
break;
}
}
Here you iterate only once and check if given number is dividable by 2 or not (i.e. this is equal to arr[i] % 2 == 0). To check if given number is prime or not, you have to check all numbers from 2 to sqrt(val).
I recommend you to select this check into separate method.
import java.util.function.IntPredicate;
final IntPredicate isPrime = val -> {
if (val < 2)
return false;
for (int i = 2, sqrt = (int)Math.sqrt(val); i <= sqrt; i++)
if (val % i == 0)
return false;
return true;
};
And your code looks much simpler:
int[] arr = { 2, 5, 9, 6, 7, 13, 2, 4, 42, 8 };
for (int val : arr) {
if (isPrime.test(val))
System.out.println("Number is prime " + val);
else
System.out.println("Number is not prime " + val);
}

you need to remove this condition in your second for loop
j <= arr[i]/2.
What you are looking for is j <= arr[i]

Related

how to implement a method to print the indices of next smaller element (in java)?

public int[] nextSmallerNumber(int[] array){}
Given an array of integers, return an array containing the indices of the next smaller number of every number or -1 if the next smaller number does not exist.
Example for clarification :
input: 10, 9, 2, 7, 6, 1, 2
output: 1, 2, 5, 4, 5, -1, -1
(((the algorithm should run in O(n) time)))
my code
public void nextSmallerNumber(int[] array) {
int next, i, j;
for (i = 0; i < array.length; i++) {
next = -1;
for (j = i + 1; j < array.length; j++) {
if (array[i] > array[j]) { next = array[j]; }}
System.out.println(i + " , " + next); }
}
but it I can't handle -1 case and I can't make it in O(n).
public static void nextSmallerNumber(int[] arr)
{
Stack<Integer> s = new Stack<Integer>();
int n=arr.length
s.push(arr[0]);
for (int i = 1; i < n; i++) {
if (s.empty()) {
s.push(arr[i]);
continue;
}
while (s.empty() == false && s.peek() > arr[i]) {
System.out.println(s.peek() + " --> " + arr[i]);
s.pop();
}
s.push(arr[i]);
}
while (s.empty() == false) {
System.out.println(s.peek() + " --> " + "-1");
s.pop();
}
}

Check whether the given number is prime or not?

I am trying to implement a code to check whether a given array of numbers is prime or not,
but when the number is not a prime number, the output displays "Prime" and "Not Prime" both answers. What is the mistake I did here and it is a pleasure to have an answer from you? Thank you in advance!
Here is my code.
Scanner scan = new Scanner(System.in);
int number = scan.nextInt();
int[] arr = new int[number];
for (int i = 0; i < number; i++) {
arr[i] = scan.nextInt();
}
for (int i = 0; i < number; i++) {
int num = arr[i];
for (int j = 2; j <= Math.sqrt(num); j++) {
if (num % j == 0 && num !=2) {
System.out.println(num + "Not prime");
break;
}
}
System.out.println(num +"Prime");
}
If you're interested in making your code a little more efficient you can go this route.
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20 };
for (int num : numbers) {
System.out.println(num + ((isPrime(num) ? " is" : " is not") + " a prime"));
}
private static boolean isPrime(int num) {
// two is a prime
if (num == 2) {
return true;
}
// numbers 1 or less or any even
// number (sans 2) are not primes
if (num <= 1 || num % 2 == 0) {
return false;
}
// Now you can check for odd divisors.
// and increment by 2 starting with 3.
for (int i = 3; i <= Math.sqrt(num); i+=2) {
if (num % i == 0) {
return false;
}
}
return true;
}
You should remember whether the number was prime or not. Your code doesn't do that so both prints are reached.
Scanner scan = new Scanner(System.in);
int number = scan.nextInt();
int[] arr = new int[number];
for (int i = 0; i < number; i++) {
arr[i] = scan.nextInt();
}
for (int i = 0; i < number; i++) {
int num = arr[i];
boolean isPrime = true;
for (int j = 2; j <= Math.sqrt(num); j++) {
if (num % j == 0 && num !=2) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println(num +"Prime");
} else {
System.out.println(num + "Not prime");
}
}
Use a boolean to track whether the number is prime. Assume it's true (prime) to begin with and set it false if it is discovered not to be prime.
boolean isPrime = true;
Afterwards, determine the message based on that boolean.
String message = isPrime ? "Prime" : "Not prime";
You can fix it for example by introducing a boolean variable:
for (int i = 0; i < number; i++) {
int num = arr[i];
boolean isPrime = true;
for (int j = 2; j <= Math.sqrt(num); j++) {
if (num % j == 0 && num !=2) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println(num +"Prime");
} else {
System.out.println(num + "Not prime");
}
}

isPrime returns different result for the same value?

This is a program that determines whether an element in an array of 10 numbers is prime or not. The prime ones will be replaced by -1 and the others remain the same when printing.
It seems fine to me, but when I run my code with 9s, some will get -1 which means 9 is a prime(wrong), some returns 9(as not prime). Why am I encountering this? Can someone help please
import java.util.Scanner;
public class Question5{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int[] array = new int [10];
for (int i = 0; i < array.length; i++){
System.out.println("Enter your number " + i);
array[i] = input.nextInt();
}
System.out.println("Before method: ");
for (int i = 0; i < array.length; i++){
System.out.print(array[i] + " ");
}
System.out.println();
prime(array);
System.out.println("After the method: ");
for (int i = 0; i < array.length; i++){
System.out.print(array[i] + " ");
}
System.out.println();
}
public static void prime(int[] list){
boolean isPrime = true;
int count = 0;
for (int i = 0; i < list.length; i++){
isPrime = true;
for (int j = 2; j < i; j++){
count = i;
if (list[i] % j == 0){
isPrime = false;
break;
}
if (list [i] == 0 || list[i] == 1){
isPrime = false;
break;
}
if (list [i] == 2){
isPrime = true;
list[count] = -1;
}
}
if (isPrime){
list[count] = -1;
}
}
}
}
You have three errors:
You are updating list[count] instead of list[i]
The condition of the inner loop is wrong. It should be j < list[i] or j *j <= list[i]
Your code identifies 0 and 1 as primes, which is incorrect. You should test if (list [i] == 0 || list[i] == 1) prior to the inner loop.
The code should look like this:
public static void prime(int[] list){
boolean isPrime = true;
int count = 0;
for (int i = 0; i < list.length; i++){
isPrime = true;
if (i < 2) {
isPrime = false;
} else {
for (int j = 2; j * j <= list[i]; j++){
count = i;
if (list[i] % j == 0){
isPrime = false;
break;
}
if (list [i] == 2){
isPrime = true;
list[i] = -1;
}
}
}
if (isPrime){
list[i] = -1;
}
}
}
For example:
Enter your number 0
0
Enter your number 1
1
Enter your number 2
2
Enter your number 3
3
Enter your number 4
4
Enter your number 5
5
Enter your number 6
6
Enter your number 7
7
Enter your number 8
8
Enter your number 9
9
Before method:
0 1 2 3 4 5 6 7 8 9
After the method:
0 1 -1 -1 4 -1 6 -1 8 9
The main logical problem which jumps out at me right away is that you are not checking for primes correctly. You should be iterating in a loop from 2 until the particular number in the array, checking for divisors. Instead, you iterate from 2 until the length of the list. Try this version:
public static void prime(int[] list) {
for (int i=0; i < list.length; ++i) {
int num = list[i];
boolean isPrime;
if (num == 1) {
isPrime = false;
}
else {
isPrime = true;
}
for (int j=2; j <= Math.sqrt(num); ++j) {
if (num % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
list[i] = -1;
}
}
return;
}
public static void main(String args[]) {
int[] list = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
prime(list);
System.out.println(Arrays.toString(list));
}
The above main() printed:
[1, -1, -1, 4, -1, 6, -1, 8, 9, 10]

How to check each variable in the array, if the next element in the array is increasing?

I'm supposed to write a program that reads an array of ints and outputs the number of "triples" in the array.
A "triple" is three consecutive ints in increasing order differing by 1 (i.e. 3,4,5 is a triple, but 5,4,3 and 2,4,6 are not).
How do I check for the "triples"?
Current Code:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// put your code here
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] array = new int[size];
int iterator = 0;
for(int i = 0; i < size; i++){
array[i] = scanner.nextInt();
} for(int j =0; j < size; j++){
iterator++;
}
}
}
The following code loops through the entire array of integers. Inside of the loop it is checked if the third integer exists inside of the array ((i + 2) < array.Length) and the other 2 conditions are all about whether value1 is the same as the value2 decreased by 1 (array[i] == array[i + 1] - 1 and array[i + 1] == array[i + 2] - 1):
for (int i = 0; i < array.Length; i++)
{
if((i + 2) < array.Length && array[i] == array[i + 1] - 1 && array[i + 1] == array[i + 2] - 1)
System.out.println("Three values at indexes" + i + " " + (i + 1) + " and " + (i + 2) + " are a triple");
}
The code below is C# and sadly not compatible to Java that easily, I'll just leave that here for anyone who wants to know how its handled in C# (the vt variable is a so called ValueTriple):
(int, int, int) vt;
for (var i = 0; i < array.Length; i++)
{
if (i + 2 >= array.Length) continue;
vt = (array[i], array[i + 1], array[i + 2]);
if (vt.Item1 == vt.Item2 - 1 && vt.Item2 == vt.Item3 - 1)
Console.WriteLine($"Three values at indexes {i}, {i + 1} and {i + 2} (Values: {array[i]}, {array[i + 1]}, {array[i + 2]}) are a triple");
}
You may try following code
import java.util.Scanner;
public class Triplet {
public static void main(String[] args) {
// put your code here
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] array = new int[size];
for(int i = 0; i < size; i++){
array[i] = scanner.nextInt();
}
Integer counter = 0;
for(int i = 0; i < size-2; i++) {
if(array[i] == array[i+1] - 1 && array[i] == array[i+2] - 2) { //checking if three consecutive ints in increasing order differing by 1
counter++;
}
}
System.out.println(counter);
}
}
Hope this will help.
A method to find out the number of triplets could look like this. You then just have to call the method depending how your input is obtained and you wish to present the result.
public static int getNumberOfTriplets(int[] toBeChecked) {
int numberOfTriplets = 0;
int nextIndex = 0;
while (nextIndex < toBeChecked.length - 2) {
int first = toBeChecked[nextIndex];
int second = toBeChecked[nextIndex + 1];
int third = toBeChecked[nextIndex + 2];
if ((first + 1 == second) && (second + 1 == third)) {
numberOfTriplets++;
}
nextIndex++;
}
return numberOfTriplets;
}
Regardless of allowing the numbers to be in more than one triplet, the answer is fairly similar in how I would personally approach it:
//determines if the input sequence is consecutive
public boolean isConsecutive(int... values) {
return IntStream.range(1, values.length)
.allMatch(i -> values[i] == values[i - 1] + 1);
}
public int countTriples(int[] input, boolean uniques) {
if (input.length < 3) {
return 0;
}
int back = 0;
for(int i = 2; i < input.length; i++) {
if (isConsecutive(input[i - 2], input[i - 1], input [i]) {
back++;
if (uniques) { //whether to disallow overlapping numbers
i += 2; //triple found, ignore the used numbers if needed
}
}
}
return back;
}
Then in calling it:
Int[] input = new int[] {1, 2, 3, 5, 6, 7, 8};
countTriples(input, true); //3
countTriples(input, false); //2

Create a new array based on another array in Java

This returns only the array a. I need to do an array that is equal to the array a but when the element is multiple of 3 i need to add the next even number. Like a=[1,3,4,6,1], the array would look like [1,7,4,6,1]. How would I do it? Thank you.
public static void main(String[] args) {
int[] a = new int[]{10, 46, 78, 32, 3, 80, 97, 11, 39, 57};
System.out.println(Arrays.toString(a));
}
public static int[] multiplos3 (int[] a){
int[] b = new int[a.length];
int j = 0;
for (int i = 0 ; i < a.length; i++){
if (a[i] % 3 == 0){
if(a[i + 1] % 2 == 0) {
b[j] = a[i] + a[i + 1];
j++;
}
}
}
System.out.println(Arrays.toString(b));
return b;
}
}
Based on a comment:
public static void multiplos3 (int[] a){
int[] b = new int[a.length]; System.arraycopy(a, 0, b, 0, a.length);
for (int i = 0 ; i < a.length; i++){
if (a[i] % 3 == 0){
for(int j = i + 1; j < a.length; j++){
if(a[j] % 2 == 0) {
b[i] = a[i] + a[j];
break;
}
}
}
}
System.out.println(Arrays.toString(b));
}
....................................................
Instead of using a[i + 1], try using another for loop to find the next even number
for(int j = i + 1; j < a.length; j++)
if(a[j] % 2 == 0)
{
[...]
break; //stop the loop after the first even number
}
The run time complexity of above mentioned code is O(N^2)
You can implement this in O(N) by first using an additional array
Try to populate this next even numbers array by traversing from the last
Below is the code
public static void multiplos3 (int[] a){
int[] b = new int[a.length];
int[] nextEvnNosArr = new int[a.length];
for (int i = a.length - 2; i > 0; i++) {
if (a[i] %2 == 0) {
nextEvnNosArr[i] = a[i];
} else {
if (nextEvnNosArr[i + 1] % 2 == 0) {
nextEvnNosArr[i] = nextEvnNosArr[i+1];
} else {
nextEvnNosArr[i] = -1;
}
}
}
for (int i = 0 ; i < a.length; i++){
if (a[i] % 3 == 0){
if (i != a.length - 1 && nextEvnNosArr[i + 1] != -1){
b[j] = a[i] + nextEvnNosArr[i + 1];
j++;
}
}
}
}
System.out.println(Arrays.toString(b));
}

Categories

Resources