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");
}
}
Related
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]
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);
}
}
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]
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
I am new here. I am trying to solve this exercise Problem 18 just for reinforcing my solving skills. I've already coded the answer. The task asks for "How many of the primes below 1,000,000 have the sum of their digits equal to the number of days in a fortnight?" (a fortnight is 14 days). My answers is 16708, but it is wrong. I hope you can help me. I don't know what my error is. I have 2 methods, 1 for generating the primes, and another for counting the digits of each prime.
This is my code:
import java.util.ArrayList;
import java.util.List;
public class Problema18 {
public static void main(String args[]) {
ArrayList<Integer> num = primes();
System.out.println(num);
count(primes());
}
public static ArrayList<Integer> primes() {
List<Integer> primes = new ArrayList<Integer>();
primes.add(2);
for (int i = 3; i <= 1000000; i += 2) {
boolean isPrime = true;
int stoppingPoint = (int) (Math.pow(i, 0.5) + 1);
for (int p : primes) {
if (i % p == 0) {
isPrime = false;
break;
}
if (p > stoppingPoint) { break; }
}
if (isPrime) { primes.add(i); }
}
// System.out.println(primes);
return (ArrayList<Integer>) primes;
//System.out.println(primes.size());
}
public static void count(ArrayList<Integer> num) {
int count = 0;
for (int i = 0; i <= num.size() - 1; i++) {
int number = num.get(i);
String num1 = String.valueOf(number);
int sum = 0;
for (int j = 0; j < num1.length(); j++) {
sum = Integer.parseInt(num1.charAt(j) + "") + sum;
if (sum == 14) { count++; }
}
System.out.println(sum);
}
System.out.println(count);
}
}
You should check whether sum == 14 outside the inner for loop. What happens now is that you also count those primes for which the sum of digits is larger than 14 but the sum of the digits in some prefix of the prime is equal to 14.
This part...
if (sum == 14) {
count++;
}
should be outside the inner for-loop - i.e. you want to do it each time you pass through the i for-loop, but not each time you pass through the j for-loop.
Like this:
public static void count(ArrayList<Integer> num) {
int count = 0;
for (int i = 0; i <= num.size() - 1; i++) {
int number = num.get(i);
String num1 = String.valueOf(number);
int sum = 0;
for (int j = 0; j < num1.length(); j++) {
sum = Integer.parseInt(num1.charAt(j) + "") + sum;
}
System.out.println(sum);
if (sum == 14) {
count++;
}
}
System.out.println(count);
}