Trying to see if the number user entered is prime in java - 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.

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

Error in checking if array members are prime or not

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

Finding the smith number between given range

I will get to the point quickly. Basically smith numbers are: Composite number the sum of whose digits is the sum of the digits of its prime factors (excluding 1). (The primes are excluded since they trivially satisfy this condition). One example of a Smith number is the beast number 666=2·3·3·37, since 6+6+6=2+3+3+(3+7)=18.
what i've tried:
In a for loop first i get the sum of the current number's(i) digits
In same loop i try to get the sum of the number's prime factors digits.
I've made another method to check if current number that is going to proccessed in for loop is prime or not,if its prime it will be excluded
But my code is seems to not working can you guys help out?
public static void main(String[] args) {
smithInrange(1, 50);
}
public static void smithInrange(int start_val, int end_val) {
for (int i = start_val; i < end_val; i++) {
if(!isPrime(i)) { //since we banned prime numbers from this process i don't include them
int for_digit_sum = i, digit = 0, digit_sum = 0, for_factor_purpose = i, smith_sum = 0;
int first = 0, second = 0, last = 0;
// System.out.println("current number is" + i);
while (for_digit_sum > 0) { // in this while loop i get the sum of current number's digits
digit = for_digit_sum % 10;
digit_sum += digit;
for_digit_sum /= 10;
}
// System.out.println("digit sum is"+digit_sum);
while (for_factor_purpose % 2 == 0) { // i divide the current number to 2 until it became an odd number
first += 2;
for_factor_purpose /= 2;
}
// System.out.println("the first sum is " + first);
for (int j = 3; j < Math.sqrt(for_factor_purpose); j += 2) {
while (for_factor_purpose % j == 0) { // this while loop is for getting the digit sum of every prime
// factor that j has
int inner_digit = 0, inner_temp = j, inner_digit_sum = 0;
while (inner_temp > 0) {
inner_digit = inner_temp % 10;
second += inner_digit;
inner_temp /= 10;
}
// System.out.println("the second sum is " + second);
for_factor_purpose /= j;
}
}
int last_temp = for_factor_purpose, last_digit = 0, last_digit_sum = 0;
if (for_factor_purpose > 2) {
while (last_temp > 0) {
last_digit = last_temp % 10;
last += last_digit;
last_temp /= 10;
}
// System.out.println("last is " + last);
}
smith_sum = first + second + last;
// System.out.println("smith num is "+ smith_sum);
// System.out.println(smith_sum);
if (smith_sum == digit_sum) {
System.out.println("the num founded is" + i);
}
}
}
}
public static boolean isPrime(int i) {
int sqrt = (int) Math.sqrt(i) + 1;
for (int k = 2; k < sqrt; k++) {
if (i % k == 0) {
// number is perfectly divisible - no prime
return false;
}
}
return true;
}
the output is:
the num founded is4
the num founded is9
the num founded is22
the num founded is25
the num founded is27
the num founded is49
how ever the smith number between this range(1 and 50) are:
4, 22 and 27
edit:I_ve found the problem which is :
Math.sqrt(for_factor_purpose) it seems i should add 1 to it to eliminate square numbers. Thanks to you guys i've see sthe solution on other perspectives.
Keep coding!
Main loop for printing Smith numbers.
for (int i = 3; i < 10000; i++) {
if (isSmith(i)) {
System.out.println(i + " is a Smith number.");
}
}
The test method to determine if the supplied number is a Smith number. The list of primes is only increased if the last prime is smaller in magnitude than the number under test.
static boolean isSmith(int v) {
int sum = 0;
int save = v;
int lastPrime = primes.get(primes.size() - 1);
if (lastPrime < v) {
genPrimes(v);
}
outer:
for (int p : primes) {
while (save > 1) {
if (save % p != 0) {
continue outer;
}
sum += sumOfDigits(p);
save /= p;
}
break;
}
return sum == sumOfDigits(v) && !primes.contains(v);
}
Helper method to sum the digits of a number.
static int sumOfDigits(int i) {
return String.valueOf(i).chars().map(c -> c - '0').sum();
}
And the prime generator. It uses the list as it is created to determine if a given
number is a prime.
static List<Integer> primes = new ArrayList<>(List.of(2, 3));
static void genPrimes(int max) {
int next = primes.get(primes.size() - 1);
outer:
while (next <= max) {
next += 2;
for (int p : primes) {
if (next % p == 0) {
continue outer;
}
if (p * p > next) {
break;
}
}
primes.add(next);
}
}
}
I do not want to spoil the answer finding, but just some simpler code snippets,
making everything simpler, and more readable.
public boolean isSmith(int a) {
if (a < 2) return false;
int factor = findDivisor(a);
if (factor == a) return false;
int sum = digitSum(a);
// loop:
a /= factor;
sum -= digitSum(factor);
...
}
boolean isPrime(int a){
for(int i = 2; i*i <= a; i++) {
if (a % i == 0) {
return false;
}
}
return true;
}
int findDivisor(int a){
for(int i = 2; i*i <= a; i++) {
if (a % i == 0) {
return i;
}
}
return a;
}
int digitSum(int a) {
if (a < 10) {
return a;
}
int digit = a % 10;
int rest = a / 10;
return digit + digitSum(rest);
}
As you see integer division 23 / 10 == 2, and modulo (remainder) %: 23 % 10 == 3 can simplify things.
Instead of isPrime, finding factor(s) is more logical. In fact the best solution is not using findDivisor, but immediately find all factors
int factorsSum = 0;
int factorsCount = 0;
for(int i = 2; i*i <= a; i++) {
while (a % i == 0) {
factorsSum += digitSum(i);
a /= i;
factorsCount++;
}
}
// The remaining factor >= sqrt(original a) must be a prime.
// (It cannot contain smaller factors.)
factorsSum += digitSum(a);
factorsCount++;
Here is the code. If you need further help, please let me know. The code is pretty self explanatory and a decent bit was taken from your code but if you need me to explain it let me know.
In short, I created methods to check if a number is a smith number and then checked each int in the range.
import java.util.*;
public class MyClass {
public static void main(String args[]) {
System.out.println(smithInRange)
}
public int factor;
public boolean smithInRange(int a, int b){
for (int i=Math.min(a,b);i<=Math.max(a,b);i++) if(isSmith(i)) return true;
return false;
}
public boolean isSmith(int a){
if(a<2) return false;
if(isPrime(a)) return false;
int digits=0;
int factors=0;
String x=a+¨" ";
for(int i=0;i<x.length()-1;i++) digits+= Integer.parseInt(x.substring(i,i+1));
ArrayList<Integer> pF = new ArrayList<Integer>();
pF.add(a);
while(!aIsPrime(pF)){
int num = pF.get(pF.size-1)
pF.remove(pF.size()-1);
pF.add(factor);
pF.add(num/factor)
}
for(int i: pF){
if((factors+"").length()==1)factors+= i;
else{
String ss= i+" ";
int nums=0;
for(int j=0;j<ss.length()-1;j++){
nums+=Integer.parseInt(ss.substring(j,j+1));
}
}
}
return (factors==digits);
}
public boolean isPrime(int a){
for(int i=2;i<=(int)Math.sqrt(a),i++){
String s = (double)a/(double)i+"";
if(s.substring(s.length()-2).equals(".0")){
return false;
factor = i;
}
}
return true;
}
public boolean aIsPrime(ArrayList<int> a){
for(int i: a) if (!isPrime(a)) return false;
return true;
}
}

Prime problems 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

Display all prime numbers based on range inputted in java

I am trying to solve a sample exercise which is to display Prime numbers based on the range inputted. For example if I inputted 10 it should output 2 3 5 7 11 13 17 19 23 29.
Here is my code:
System.out.print("Enter Range: ");
int range = input.nextInt();
int r = 0;
for(int ctr1 = 2; ctr1 <= range; ctr1++){
for(int ctr2 = 1; ctr2 <= ctr1; ctr2++){
if(ctr1%ctr2 == 0){
r++;
}
}
if(r == 2){
System.out.println(ctr1);
}
}
What happens is when I input 10 it just outputs 2. Can anyone please tell me the error in my codes?
Thanks...
Using nested loop in this case could make things more complicated. I would suggest you to divide the solution into two steps:
create a function to determine if a number is prime.
private static 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;
}
find the first N prime numbers with a loop:
System.out.print("Enter Range: ");
int range = input.nextInt();
int count = 0;
for (int number = 2; count < range; number++) {
if (isPrime(number)) {
count++;
System.out.println(number);
}
}
I didnt understand your code. Try to give reasonable parameter names. Anyway this the code that you are looking for.
public static void main(String args[]) {
//get input till which prime number to be printed
System.out.println("Enter the amount of prime numbers to be printed: ");
int limit = new Scanner(System.in).nextInt();
int count=1;
//printing primer numbers till the limit ( 1 to 100)
System.out.println("Printing prime number from 1 to " + limit);
for(int number = 2; count<=limit; number++){
//print prime numbers only
if(isPrime(number)){
System.out.println(number);
count++;
}
}
}
/*
* Prime number is not divisible by any number other than 1 and itself
* #return true if number is prime
*/
public static boolean isPrime(int number){
for(int i=2; i<number; i++){
if(number%i == 0){
return false; //number is divisible so its not prime
}
}
return true; //number is prime now
}
One more solution)
public static boolean checkPrime(int i) {
if (i <= 1)
return false;
else if (i <= 3)
return true;
else if (i % 2 == 0 || i % 3 == 0)
return false;
int n = 5;
while (n * n <= i) {
if (i % n == 0 || i % (n + 2) == 0)
return false;
n = n + 6;
}
return true;
}
public static void main(String[] args) throws Exception {
int isPrime = 0;
int counter = 0;
int size = 10;
while (isPrime < size) {
counter++;
if (checkPrime(counter)) {
isPrime++;
System.out.println(counter);
}
}
}

Categories