I'm supposed to scan an integer array, and loop through it, printing "Prime" or "Not prime" depending on whether the integer is a prime number or not.
It's correct in some cases, while wrong on others (like 33 as an example). Here's my code:
public class Solution {
public static void main(String[] args) {
//Declaring the scanner
Scanner scan = new Scanner(System.in);
//Getting the number of integers to scan
int n = scan.nextInt();
//Declaring a numbers array
int[] numbers = new int[n];
//Scanning the integers
for(int i=0; i<n; i++)
numbers[i] = scan.nextInt();
//Determining if numbers are prime
for(int i=0; i<n; i++)
{
boolean isPrime = true;
for(int j=2; j<n; j++)
{
if(numbers[i] % j == 0){
isPrime = false;
System.out.println("Not prime");
break;
}
}
if(isPrime)
System.out.println("Prime");
}
}
}
Two important points you can consider:
A. You need to check numbers up to its square root i.e. if an integer is not divisible by any integer from 2 to its square root, it is Prime
B. You do not need an additional boolean flag (i.e. isPrime in your code).
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
// Declaring the scanner
Scanner scan = new Scanner(System.in);
// Getting the number of integers to scan
System.out.print("How many numbers: ");
int n = scan.nextInt();
// Declaring a numbers array
int[] numbers = new int[n];
// Scanning the integers
for (int i = 0; i < n; i++) {
System.out.print("Enter number " + (i + 1) + ": ");
numbers[i] = scan.nextInt();
}
// Determining if numbers are prime
for (int i = 0; i < n; i++) {
int j, upperRange = (int) Math.sqrt(numbers[i]);
for (j = 2; j <= upperRange; j++)
if (numbers[i] % j == 0)
break;
if (numbers[i] != 1 && j > upperRange)
System.out.println(numbers[i] + " is Prime");
else
System.out.println(numbers[i] + " is not Prime");
}
}
}
A sample run:
How many numbers: 5
Enter number 1: 256
Enter number 2: 289
Enter number 3: 1
Enter number 4: 5
Enter number 5: 7
256 is not Prime
289 is not Prime
1 is not Prime
5 is Prime
7 is Prime
Consolidating the code and using Math.sqrt()
Refactor your code to to this
public boolean isPrime(int number){
if(number==1){
return false;
}
boolean isPrime = true;
int maxN = Math.ceil(Math.sqrt(number));
for(int j=2; j< maxN; j++){
if(number % j == 0){
isPrime = false;
break;
}
}
return isPrime;
}
Here's the updated code
public class Solution {
public static void main(String[] args) {
//Declaring the scanner
Scanner scan = new Scanner(System.in);
//Getting the number of integers to scan
int n = scan.nextInt();
//Declaring a numbers array
int[] numbers = new int[n];
//Scanning the integers
for(int i=0; i<n; i++)
numbers[i] = scan.nextInt();
//Determining if numbers are prime
for(int i=0; i<n; i++)
{
checkPrime(numbers[i]);
}
}
private static void checkPrime(int number) {
boolean isPrime = true;
int limit = (int) Math.ceil(Math.sqrt(number));
for(int j=2; j<=limit; j++)
{
if(number >2 && number % j == 0){
isPrime = false;
break;
}
}
if(number> 1 && isPrime)
System.out.println(number + " is Prime");
else
System.out.println(number + " is not prime");
}
}
Sample output
> 5
> 1 2 3 4 33
1 is not prime
2 is Prime
3 is Prime
4 is not prime
33 is not prime
Related
In short, again I found the task on internet:
Input integers from the keyboard, check whether prime numbers or not. When you input 0, the program ends.
So far, I wrote the logic for checking the integer if it's prime or not. The main stumbling block was that I should read several integers from one string and stop program if last integer is 0. So when I tried to add a loop to iterate over the input and check whether the integer is prime or not, my logic doesn't work and it returns only 1 st integer without others.
import java.util.Scanner;
public
class PrimeNumber
{
public
static void main(String[] args)
{
int temp;
boolean isPrime = true;
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int[] arr = new int[num];
for (int i = 0; i < arr.length; i++)
{
arr[i] = sc.nextInt();
for (int y = 2; y <= num / 2; i++)
{
temp = num % i;
if (temp == 0)
{
isPrime = false;
break;
}
}
}
if (isPrime)
System.out.println(num + " is a Prime Number");
else
System.out.println(num + " is not a Prime Number");
}
}
I recommend if you can check this link: Check if an int is prime Java
Write a boolean function that checks an integer if it is prime or not. You do not need to create a O N^2 algorithm from input box.
Step 1: Check one integer and see if returns true( means it is prime )
Step 2: Try random numbers and see if they work as well.
Step 3: Add an array and see if contents of the array has prime numbers or not. Then you can print out any message you like.
See this example from the same reference to get started.
https://onecompiler.com/java/3y2cxy9ea
Your thought process was good.
The snippet with the if-else statement is outside of the for loop, so it will only happen once.
The value of num is just the number of int values the user will type in (basically arr.length). It should instead be checking primality of arr[i]. If arr[i] is divisible by some number other than 1 or arr[i], it is not prime. Also, if arr[i] is not greater than 1, it is not prime, either.
Lastly, make sure isPrime gets reset to true.
I recommend adding instructions in the form of print(), so it becomes clearer which number is which:
public static void main(String[] args)
{
int temp;
boolean isPrime;
Scanner sc = new Scanner(System.in);
System.out.print("Number of integer values: ");
int numberOfInts = sc.nextInt();
int[] arr = new int[numberOfInts];
for (int i = 0; i < numberOfInts; i++)
{
isPrime = true;
System.out.print("Int " + (i+1) + " = ");
arr[i] = sc.nextInt();
for (int y = 2; y <= arr[i] - 1; y++)
{
temp = arr[i] % y;
if (temp == 0)
{
isPrime = false;
break;
}
}
if (arr[i] <= 1) {
isPrime = false;
}
if (isPrime)
System.out.println(arr[i] + " is a Prime Number");
else
System.out.println(arr[i] + " is not a Prime Number");
}
}
As for exiting the program, put this at the start of the enclosing for loop:
if (arr[i] == 0) {
break;
}
There are better solutions than this, but on a basic level, this is fine.
You can try using this function to check that the number is prime:
private static boolean isPrime(int number) {
return java.math.BigInteger.valueOf(number).isProbablePrime((int) Math.log(number));
}
Then you can iterate through the array and check each of its elements with this function
My version of this program:
public class Main {
public static void main(String[] args) {
try(java.util.Scanner sc = new java.util.Scanner(System.in)) { //use try-with-resources block to avoid resources leak
//filling an array
int[] ints = new int[sc.nextInt()];
//if program gets 0, it stops filling
for(int i = 0; i < ints.length; i++) {
int temp = sc.nextInt();
if(temp == 0) break;
ints[i] = temp;
}
//check
for(int i = 0; i < ints.length; i++)
if(ints[i] != 0) System.out.printf("%s is%s a prime number.\n", ints[i], isPrime(ints[i]) ? "" : "n't");
}
}
private static boolean isPrime(int number) { //Some maths
return java.math.BigInteger.valueOf(number).isProbablePrime((int) Math.log(number));
}
}
I am a noob at programming so I might have trouble with some key terms.
I'm trying to write a program where a user types in a minimum number and a maximum number and it generates a random number. After that I want to know how many even numbers and odd numbers are in the random generated number. I was able to successfully complete the first part but I am having trouble detecting how many even and odd numbers are in the random generated number.
SAMPLE OUTPUT:
Ex:
Random generated number is: 478,099
# of even digits: 2
# of odd digits: 3
I tried creating local variables that did not work, I want to use a switch case statement but I am having trouble. For now I used a for loop but I want to use a switch case.
public static void main(String[] args)
{
DecimalFormat fmt = new DecimalFormat("###,###,###,###,###");
Scanner scanner = new Scanner(System.in);
int max = -1;
int min = 0;
int [] diffvalue = new int [1];
System.out.println("Enter in a maximum value: ");
max = scanner.nextInt();
System.out.println("Enter in a minimum value: ");
min = scanner.nextInt();
if (min > max)
{
System.out.println("Your minimum value is greater then your
maximum value.");
}
for (int i = 0; i < diffvalue.length; i++)
{
diffvalue[i] = (int)(Math.random()*(max-min)+min);
}
System.out.println("Random Value: ");
for(int i = 0; i < diffvalue.length; i++)
{
System.out.println(fmt.format(diffvalue[i]));
}
}
int l = diffvalue[i];
while (l > 0)
{
switch ((l % 10) % 2)
{
case 1:
odd++;
break;
default:
even++;
}
l /= 10;
}
}
I can't look at the whole number separately.
**EDIT 1**
import java.util.Scanner;
import java.text.DecimalFormat;
public class MyClass
{
public static void main(String args[])
{
DecimalFormat fmt = new DecimalFormat("###,###,###,###,###");
Scanner scanner = new Scanner(System.in);
int max = -1;
int min = 0;
int [] diffvalue = new int [1];
System.out.println("Enter in a maximum value: ");
max = scanner.nextInt();
System.out.println("Enter in a minimum value: ");
min = scanner.nextInt();
int even = 0; int odd = 0;
if (min > max)
{
System.out.println("Your minimum value is greater then your
maximum value.");
}
for (int i = 0; i < diffvalue.length; i++)
{
diffvalue[i] = (int)(Math.random()*(max-min)+min);
}
System.out.println("Random Value: ");
for(int i = 0; i < diffvalue.length; i++)
{
System.out.println(fmt.format(diffvalue[i]));
}
for(int i = 0; i < diffvalue.length; i++)
{
int l = diffvalue[i];
while (l > 0)
{
switch ((l % 10) % 2)
{
case 1:
odd++;
break;
default:
even++;
}
l /= 10;
}
System.out.println("Even:" + even);
System.out.println("Odd: " + odd);
}
}
}
I have gotten it to detect the even numbers and the odd numbers now I am curious to know if there is a way to do it without having the the two variables (odd, even).
You are not dividing the value l by 10. Which is why it is going into a infinite loop.
public static void even(int[] diffvalue)
{
int even = 0;
for(int i = 0; i < diffvalue.length; i++)
{
int l = diffvalue[i];
while (l > 0)
{
if((l % 10)%2==0) // this line is changed
{
even++;
}
l = l/10; // this line is changed
}
}
}
Also, if you are checking for even, you have to do ...%2 == 0. Find your errors fixed in the code above.
EDIT: you can also calculate the odd numbers in the same loop, like this:
if((l % 10)%2==0) // this line is changed
{
even++;
}
else
{
odd++;
}
EDIT3: The code was supposed to go inside the method, not replace the method.
I do not see any use case for a switch case here, but it can be accommodated like this:
public static void even(int[] diffvalue)
{
int even = 0;
for(int i = 0; i < diffvalue.length; i++)
{
int l = diffvalue[i];
while (l > 0)
{
switch ((l % 10) % 2)
{
case 1:
odd++;
break;
default:
even++;
}
l /= 10;
}
}
Hope this helps. Good luck.
I'm having issues getting all prime numbers between a given integer A and integer B.
The issue is that the output goes well beyond whatever I defined for B. I thought that the
if (isPrime){
count++;
would fix this but the output still goes well beyond the intended number of integer B.
For example if int valueA = 1 and int valueB = 100, it'll get prime numbers from around 1 to 500 before stopping, instead of just ending the check at 100.
Thank you for any assistance.
import java.util.*;
public class PrimeNumbersTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
// Ask user to input an integer value for A and B
System.out.print("Enter the value of A (must be an integer): ");
int valueA = input.nextInt();
System.out.print("Enter the value of B (must be an integer): ");
int valueB = input.nextInt();
System.out.println("The prime numbers between " + valueA + " and " + valueB + " are:");
final int LINE = 10;
int count = valueA;
int number = 2;
while (count < valueB) {
// Assume the number is prime
boolean isPrime = true;
// Test if number is prime
for (int divisor = 2; divisor <= number / 2; divisor++) {
if (number % divisor == 0) { // If true number is not prime
isPrime = false; // Set isPrime to false
break; // Exit the for loop
}
}
if (isPrime) {
count++;
if (count % LINE == 0) {
System.out.println(number);
}
else
System.out.print(number + " ");
}
number++;
}
}
}
When you want to work on a range of number, use a for loop instead of while loop to reduce confusion. You obviously want
for(int number = valueA; number <= valueB; number++){/*check if number is prime*/}
Example:
public static void main(String []args){
int valueA = 1;
int valueB = 100;
int count = 0;
for(int number = valueA; number <= valueB; number++)
{
if(isPrime(number))
{
count++;
System.out.println(number);
}
}
System.out.println("count = " + count);
}
public static boolean isPrime(int n)
{
for(int i = 2; i*i <= n; i++)
{
if(n % i == 0)
{
return false;
}
}
return n > 1;
}
For your requirement of checking isPrime inline:
public static void main(String []args){
int valueA = 1;
int valueB = 100;
int count = 0;
for(int number = valueA; number <= valueB; number++)
{
boolean isPrime = number > 1;
for(int i = 2; i*i <= number; i++)
{
if(number % i == 0)
{
isPrime = false;
break;
}
}
if(isPrime)
{
count++;
System.out.println(number);
}
}
System.out.println("count = " + count);
}
I'm unsure of how to create a sequence of numbers that can be placed before each iteration of printed prime numbers. Thank you for any help you can offer.
public class CountingPrimes {
public static void main(String[] args) {
int flag = 0, i, j;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the 1st number: ");
int firstNum = sc.nextInt();
System.out.println("Enter the 2nd number: ");
int secondNum = sc.nextInt();
System.out.println("Counting prime numbers between "
+ firstNum + " and " + secondNum + ":");
for (i = firstNum; i <= secondNum; i++) {
for (j = 2; j < i; j++) {
if (i % j == 0) {
flag = 0;
break;
} else {
flag = 1;
}
}
if (flag == 1) {
System.out.println(i);
}
}
}
}
Right now, my code outputs (after the user enters their two numbers):
Counting prime numbers between 1 and 14:
3
5
7
11
13
What I need my code to look like:
Counting prime numbers between 1 and 14:
1. 3
2. 5
3. 7
4. 11
5. 13
Also, if you could see any errors or improvements I could change, I would greatly appreciate it. Thank you again!
You can use a counter and print the counter as you print the prime number. Increment the counter each time.
int counter = 1;
int flag = 0, i, j;
.....
if (flag == 1) {
System.out.format("%d. %d\n", counter, i);
counter++;
}
a simple change:
import java.util.Scanner;
public class CountingPrimes {
public static void main(String[] args) {
int flag = 0, i, j;
int count = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the 1st number: ");
int firstNum = sc.nextInt();
System.out.println("Enter the 2nd number: ");
int secondNum = sc.nextInt();
System.out.println("Counting prime numbers between "
+ firstNum + " and " + secondNum + ":");
for (i = firstNum; i <= secondNum; i++) {
for (j = 2; j < i; j++) {
if (i % j == 0) {
flag = 0;
break;
} else {
flag = 1;
}
}
if (flag == 1) {
System.out.println(++count + "." + i);
}
}
}
}
Just add a count variable and increment it whenever you output a number:
...
int count = 0;
for (i = firstNum; i <= secondNum; i++) {
...
if (flag == 1) {
count++;
System.out.format("%d. %d%n", count, i);
}
}
Declare Count before for loop
int count = 0;
and then increment the count on every prime number.
if (flag == 1) {
System.out.println(++count+". "+i);
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int N = 0;
do {
System.out.println("How long should we search for primes? Until N=: ");
N = scan.nextInt();
} while (N <= 2); // gets the amount of prime numbers there are that go up to that number
//example, if user enters 20, the output will be that there are 8 prime numbers
boolean[] prime = new boolean[N +2];
for (int i = 2; i <= N; i++) {
prime[i] = true; //makes all values in the array true
}
for (int i = 2; i * i <= N; i++) {
if (prime[i]) {
for (int z = i; z * i <= N; z++) {
prime[i * z] = false; // makes the non prime numbers in the array false
int newCheck = 0;
do {
System.out.println("Enter a number to see if it is prime");
int go = 0;
newCheck = scan.nextInt(); //here's where i need help
} while (newCheck <= 1 || newCheck > N);
if(prime[newCheck]){ // if the number entered is true in the array, it is prime
System.out.println("It is prime");
int mPrime=(int)((Math.log(newCheck))/(Math.log(2)))-1;
if (prime[mPrime]){//ignore this, its for another part i need to do
System.out.println(""+newCheck+ "is a merseinne prime number! It equals 2^"+mPrime+ " -1");
}
}
else if (prime[newCheck]==prime[i*z]){ //if the number is equal to false in the array,
//it is not prime
System.out.println("It is not prime");
}
if(newCheck==0){
break;
}
}
}
}
int counterPrime = 0;
for (int i = 2; i <= N; i++) {
if (prime[i]) {
counterPrime++;
}
}
System.out.println("The number of primes less than or equal to " + N + " is " + counterPrime);
}
I need help with trying to output to the user that the number they entered is prime. So far this example only works for some numbers. The program thinks 14 is prime, 12 is prime, 25 is prime, 35 is prime,36 is prime,39 is prime,and that 34 is prime.
It gets some numbers right though. It knows 8, 10, 12,18 and some other numbers are not prime.
Here is a little method to help you along:
public static boolean isPrime(final int number) {
int temp;
boolean isPrim = true;
for(int i=2; i <= number / 2; i++) {
temp = number%i;
if(temp==0) { isPrim = false; break; }
}
return isPrim;
}
Hope this helps.