Prime problems java - java

A prime number is a positive integer greater than 1 that is divisible only by itself and 1. In this assignment you are responsible to write a complete Java program to display first N prime numbers. In other words, your program should list the first N prime numbers.
Functional Requirements
Your program should prompt the user for a positive number, or a value of -1 to terminate the program. If the user enters 0, or a negative number, the program will also end immediately.
Your program will display the first N prime numbers given by the user. For example, if the user enters 3, the program should display: “2, 3, 5” which are the first three prime numbers. If the user enters 6, the output would be: “2, 3, 5, 7, 11, 13”.
Sample Run
Welcome to the list of N prime numbers program!
===============================================
Please enter the value of N (positive integer):
6
First 6 prime numbers are:
2
3
5
7
11
13
When i worked on it i got this but need help finishing
import java.util.Scanner;
public class prime {
public static void main(String[] args) {
System.out.print("Welcome to the list of N prime numbers program! \n========================================================\nPlease enter the value of N (positive integer): ");
Scanner scan = new Scanner(System.in);
int n;
int status=1;
int num=3;
n = scan.nextInt();
if(n>=1) {
System.out.println(2);
for(int count=2; count<=n; count++) {
for(int j=2; j<=Math.sqrt(num);j++) {
if(num%j==0) {
status =0;
break;
}
if(status!=0) {
System.out.println(num);
count++;
}
}
status=1;
num++;
}
}
}
}

you should give a out.println("enter the number of prime numbers needed");
then read it using scanner(for example if it is reading into x) and provide a if condition as
if(x<=0)
{
break;
}
and balance code can be given in the else condition.

public class prime {
public static boolean isPrime(int n) {
for(int j=2; j<=Math.sqrt(n)+1;j++) { //Math.sqrt(n) + 1 because you want to check more than half of the original value.
if(n%j==0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
System.out.print("Welcome to the list of N prime numbers program! \n========================================================\nPlease enter the value of N (positive integer): ");
Scanner scan = new Scanner(System.in);
int inputNum; //try making the variable name meaningful
inputNum = scan.nextInt();
int count = 0;
int startingVal = 2;
while(count<inputNum) {
if(inputNum==-1) {
break;
}
if(count==0) {
System.out.println(2);
count++;
}
else if(isPrime(startingVal)) {
System.out.println(startingVal);
count++;
}
startingVal ++;
}
}
}
This should work fine. As #Amadan in the comment section already mentioned, your program did not work because your if(status!=0) is in the for loop.
Also, setting the variable names meaningful helps you fix or edit your code easier.

please use below method to get prime no.
static List<Integer> nthPrimeNo(int nth){
List<Integer> integers = new ArrayList<>();
int num, count, i;
num=2;
count=0;
for (int j = 0; j < nth; j++) {
while (count < j){
num=num+1;
for (i = 2; i <= num; i++){
if (num % i == 0) {
break;
}
}
if ( i == num){
count = count+1;
}
}
integers.add(num);
}
return integers;
}
Or do you want to get 10 greater than primes number,
static List<Integer> sieveOfEratosthenes(int n) {
boolean prime[] = new boolean[n + 1];
Arrays.fill(prime, true);
for (int p = 2; p * p <= n; p++) {
if (prime[p]) {
for (int i = p * 2; i <= n; i += p) {
prime[i] = false;
}
}
}
List<Integer> primeNumbers = new LinkedList<>();
for (int i = 2; i <= n; i++) {
if (prime[i]) {
primeNumbers.add(i);
}
}
return primeNumbers;
}

use this function call System.exit(0); in exit condition

Related

Java isPrime function: Check if input integer values are prime

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));
}
}

getting the prime numbers scanner [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last year.
Improve this question
I am using the below code and it's giving me the option to enter the final value but I need to give input of two values and also the total count of prime numbers between that range.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter two positive integers: ");
int input = scanner.nextInt();
List<Integer> primes = new ArrayList<>();
// loop through the numbers one by one
for (int i = 2; i < input; i++) {
boolean isPrimeNumber = true;
// check to see if the number is prime
for (int j = 2; j < i; j++) {
if (i % j == 0) {
isPrimeNumber = false;
break; // exit the inner for loop
}
}
// print the number if prime
if (isPrimeNumber) {
primes.add(i);
}
}
System.out.println("The number of prime is: " + primes.size());
System.out.println(primes.toString());
}
Your but fine but not exactly as you've described.
scanner.nextInt() - can produce only one int value (or causes InputMismatchException if input isn't an int).
You said 'i need to give input of two values' - to accomplish it you may have to read these values separately using nextInt() or you can read both as a line, then split the line, and parse to int separately.
The first option is definitely easier.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter two positive integers: ");
System.out.print("start = ");
int start = scanner.nextInt();
System.out.print("end = ");
int end = scanner.nextInt();
List<Integer> primes = new ArrayList<>();
// loop through the numbers from start to end inclusive
for (int i = start; i <= end; i++) {
// check if i is prime
if (isPrime(i)) {
primes.add(i);
}
}
System.out.println("The number of prime is: " + primes.size());
System.out.println(primes);
}
private static boolean isPrime(int i) {
boolean isPrime = true;
// check to see if the number is prime
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
isPrime = false;
break; // exit the inner for loop
}
}
return i != 1 && isPrime;
}
Let us know, please, is that what you wanted to achieve?
MORE PERFORMANT IMPLEMENTATION
In this implementation, all functionality for finding primes resides in the separate class PrimeUtil.
The constructor of this class is private and to create an instance of this class, it provides a static method getInstance() which accepts two integer numbers representing the desired range.
This is done in order to initialize the object by invoking the init() method and return a fully-fledged object primeUtil, containing the result to the caller.
Method init() populates primes list. All discovered prime numbers will be added to it.
primes list acts as cash. There's no need to rediscover primes over and over again like it's dome in the first solution. That drastically improves the performance.
Another optimization is the way to determine the next probable prime implemented in the method getNextCandidate().
The mathematical logic behind this method is based on the fact that all numbers, that are evenly divisible by 2 and 3 are already eliminated because 2 and 3, are added to the primes list by default and there is no need to consider any number that is divisible 2 or 3. From this fact we can make a conclusion that the remainder of division by 6 for every potential prime cant be equal: 0; 2; 3; 4. I.e. valid prime must fulfill the condition prime % 6 == 1 || prime % 6 == 5.
main
public static void main(String[] args) {
printPrimes();
}
public static void printPrimes() {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter two positive integers: ");
System.out.print("start = ");
int start = scanner.nextInt();
System.out.print("end = ");
int end = scanner.nextInt();
List<Integer> primes = PrimeUtil.getInstance(start, end).getResult();
System.out.println("The number of prime is: " + primes.size());
System.out.println(primes);
}
PrimeUtil class
import java.util.ArrayList;
import java.util.List;
import static java.lang.Math.*;
import static java.util.stream.Collectors.toUnmodifiableList;
public class PrimeUtil {
private final List<Integer> primes;
private final int loBound;
private final int hiBound;
private PrimeUtil(int loBound, int hiBound) {
this.primes = new ArrayList<>();
this.loBound = loBound;
this.hiBound = hiBound;
}
public static PrimeUtil getInstance(int loBound, int hiBound) {
PrimeUtil primeUtil = new PrimeUtil(max(loBound, 2), hiBound);
primeUtil.init();
return primeUtil;
}
private void init() {
if (loBound <= 2) primes.add(2);
if (loBound <= 3) primes.add(3);
int candidate = 5;
while (candidate <= hiBound) {
if (isPrime(candidate)) {
primes.add(candidate);
}
candidate = getNextCandidate(candidate);
}
}
private boolean isPrime(int candidate) {
boolean isPrime = true;
for (int i = 0; i < primes.size() && primes.get(i) <= sqrt(candidate); i++) {
if (candidate % primes.get(i) == 0) {
isPrime = false;
break;
}
}
return isPrime;
}
private int getNextCandidate(int candidate) {
return candidate % 6 == 5 ? candidate + 2 : candidate + 4;
}
public List<Integer> getResult() {
return primes.stream()
.dropWhile(i -> i < loBound)
.collect(toUnmodifiableList());
}
}
All you need is to ask the user for two integer numbers using Scanner two times.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter two positive integers:");
System.out.print("low range: ");
int lo = scan.nextInt();
System.out.print("high range: ");
int hi = scan.nextInt();
List<Integer> primes = getPrimeNumbers(lo, hi);
System.out.println("The number of prime is: " + primes.size());
System.out.println(primes);
}
private static List<Integer> getPrimeNumbers(int lo, int hi) {
List<Integer> primes = new ArrayList<>();
for (int i = lo; i <= hi; i++)
if (isPrime(i))
primes.add(i);
return primes;
}
private static boolean isPrime(int val) {
if (val == 1)
return false;
if (val == 2 || val == 3)
return true;
for (int i = 2, sqrt = (int)Math.sqrt(val); i <= sqrt; i++)
if (val % i == 0)
return false;
return true;
}
use two Scanners to get second input
you can remove the list and adding elements to it and use a counter if you want only the number of prime numbers :)
So the solution would be :
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter the first positive integer: ");
int firstNumber = scanner.nextInt();
System.out.println("Please enter the second positive integer: ");
// you should have another scanner hence an other text output to invite user
int secondNumber = scanner.nextInt();
List<Integer> primes = new ArrayList<>(); // we do not really need this if we want only the number of prime number and not the list but i'll use it for you anyway
for(int i = firstNumber; i <= secondNumber; i++) //the use the input variables
{
if (isPrime(i)){ // we made a function here to make things clear. it's role to tell weather a number is a prime or not
primes.add(i); // we add prime numbers to this list as you used a list. You can go for an easier solution just a counter++ each time ;)
}
}
System.out.println("The number of prime numbers in this range is: " + primes.size());
}
static boolean isPrime(int num){
if (num <= 1)
return false;
for(int i = 2; i * i <= num; i++)
// If a divisor of n exists
if (num % i == 0)
return false;
return true;
}

Trying to see if the number user entered is prime in java

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.

Check to see what two prime numbers are around a number from the user

I am supposed to write a program that accepts a value from the user greater (than two of course) and print out the two prim numbers closest to it. I am supposed to use a method to simplify the process.
For example, if the user inputted 24 the two numbers are 23 and 29.
I am just confused about the math behind it. How would I go about doing this? I just want somebody to put me on the right track. Thanks a ton
I did sthg like this;
I write two for loop to scan both side, and a prime method to find prime numbers.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int minPrime = 0;
int maxPrime = 0;
System.out.println("Please give a number ");
int number = scanner.nextInt();
for (int i = number - 1; i > 2; i--) {
if (isPrime(i)) {
minPrime = i;
break;
}
}
for (int i = number + 1; i < Integer.MAX_VALUE; i++) {
if (isPrime(i)) {
maxPrime = i;
break;
}
}
System.out.println(minPrime);
System.out.println(maxPrime);
}
static boolean isPrime(int n) {
if (n < 2)
return false;
for (int i = 2; i < n; i++) {
if (n % i == 0)
return false;
}
return true;
}
There are several Possibilities to calculate Prime Numbers. E.g. sieve of Eratosthenes or sieve of Atkin
You can have a "cached" list of first 100/1000/10000 prime numbers and if input of user is within this range you just have to find two numbers which are closest to user input.
Then you can use something like (with some ifs to sort out cases of user input at beginning/end of list)
for(int i=0;i<cache.size();i++){
if(userNumber<cache.get(i)){
indexOfSmallerPrimeNumber = i;
}
}
int smallerPrimeNumber = cache.get(indexOfSmallerPrimeNumber);
int biggerPrimeNumber = cache.get(indexOfSmallerPrimeNumber+1);
When user will input numbers bigger than your cache then you'll have compute next numbers (which may be time consuming for big numbers). You can use for this purpose sieve of Eratosthenes algorithm.
This might help you...
You can customize it as per your need. It worked perfectly while my testing.
import java.util.Scanner;
class Prime {
static boolean isPrime(int val)
{
for(int i=val/2;i>1;i--)
{
if(val%i==0)
return false;
}
return true;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number:");
int num=input.nextInt();
for(int i=num-1;i>2;i--)
{
if(isPrime(i))
{
System.out.println("First prime no.: "+i);
break;
}
}
for(int i=num+1;;i++)
{
if(isPrime(i))
{
System.out.println("Second prime no.: "+i);
break;
}
}
input.close();
}
}

Incorrect output with counting

I was coding on a program that would keep on accepting numbers until the user enters -1. Then it would display the number of items that are divisible by 9; using a special property- sum of digits of numbers that are divisible by 9, are themselves divisible by 9. I have been told to rely on a heavily modular approach. Simple input, no arrays.
There is no compilation errors and stuff, but the value of count is always wrong. For instance, if I input 18,18,4,4,2,5,19,36,-1, the expected output is 3, but the output comes out as 4. I have no clue why. I have tried count++ and ++count, they yield the same output. Where am I going wrong?
import java.util.Scanner;
public class Div{
static Scanner sc = new Scanner(System.in); boolean run = true; static int n = 0;
static int count = 0;
public static void main(String[] args){
Div a = new Div();
a.accept();
a.display();
}
void accept(){
while (run){
System.out.println("Enter the number");
n = sc.nextInt();
if (isDivisibleByNine(n)){
count = count + 1;
}
if (n == -1){
run = false;
}
}
}
static int sumOfDigits(int a){
int m = a; int sum = 0;
while (m>0){
sum = sum + (m%10); m /= 10;
}
return sum;
}
static boolean isDivisibleByNine(int x){
if (sumOfDigits(x)%9==0){
return true;
}
else {
return false;
}
}
void display(){
System.out.println("The total number of numbers that are divisible are: " + count);
}
}
The problem is with your end value -1. For -1 also your sumOfDigits function will return 0. so only count is incremented by 1 always.
while (run){
System.out.println("Enter the number");
n = sc.nextInt();
if (n == -1){
break; //Break if the end of input reached.
}
if (isDivisibleByNine(n)){
count = count + 1;
}
}
The final number that your program believes is divisible by 9 is your -1.
You go through the complete loop for it - your sum only goes while the number is above 0, so it terminates immediately and returns 0. 0 % 9 is 0, so it increments your counter then ends. Check for this by changing your loop:
if (n == -1){
run = false;
}
else if (isDivisibleByNine(n)){
count = count + 1;
}
You are not computing the sum of digits.
This is how you compute it :
static int sumOfDigits(int a){
int m = a; int sum = 0;
while (m>0){
sum = sum + (m%10);
m /= 10;
}
return sum;
}
EDIT (after your fix of sumOfDigits) :
You get the wrong count because you also check if -1 is divisible by 9, and it returns true, because sumOfDigits doesn't handle negative integers properly.
Here's an easy fix:
void accept(){
while (run){
System.out.println("Enter the number");
n = sc.nextInt();
if (n == -1){
run = false;
}
else if (isDivisibleByNine(n)){
count = count + 1;
}
}
}
change as this .
static boolean isDivisibleByNine(int x){
if(x>0){
if (sumOfDigits(x)%9==0){
return true;
}
else {
return false;
}
}else{
return false;
}
}

Categories