I want to display the prime number required by the user. For example, if the user wants 3rd prime, I will display 5. I have the following java code.
import java.util.Scanner;
public class Prime {
private static Scanner scanner;
public static void main(String args[]) {
//get input till which prime number to be printed
// System.out.println("Enter which prime number to be printed: ");
// scanner = new Scanner(System.in);
// int limit = scanner.nextInt();
int count = 0;
int number = 2;
//System.out.println("Printing prime number from 1 to " + limit);
while(count<=3)
{
if(isPrime(number)){
count++;
// System.out.println(count);
}
number++;
}
if(count == 3)
System.out.println("10001 prime is "+number);
}
public static boolean isPrime(int number){
for(int i=2; i<number; i++){
if(number%i == 0){
return false;
}
}
return true;
}
}
When i run it, I am not able to gett any output. Where am i going wrong?
PS: For time being, I am running the loop only until 3.
You have while(count <= 3) so when you exit the loop, count == 4.
Therefore, your if(count == 3) is never entered and nothing is printed.
Anyways the better solution would be
public void calcPrime(int inp) {
ArrayList<Integer> arr = new ArrayList<Integer>();
arr.add(2);
arr.add(3);
int counter = 4;
while(arr.size() < inp) {
if(counter % 2 != 0 && counter%3 != 0) {
int temp = 4;
while(temp*temp <= counter) {
if(counter % temp == 0)
break;
temp ++;
}
if(temp*temp > counter) {
arr.add(counter);
}
}
counter++;
}
System.out.println("finish" +arr.get(inp-1));
}
}
Here is corrected code that works.
public class Main {
public static void main(String args[]) {
//Returns fourth prime number
System.out.println(getPrimeNumber(4));
}
public static int getPrimeNumber(int order) {
int currentOrder = 1;
int currentNumber = 1;
while (currentOrder < order) {
currentNumber++;
if (isPrime(currentNumber)) currentOrder++;
}
return currentNumber;
}
public static boolean isPrime(int number) {
for (int i = 2; i < number; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
There was no need to start your counter at 0 and it mathematically wrong to start with number 2 ! Just begin with order and currentNumber initialized at 1 and if first prime number is what your user is looking for, no loop will be required !
Also, your loop condition after correct variable initialization was corrected from "<=" to "<".
That's all !
Related
I'm trying to write a program that asks the user to enter a number, then I need to create a method called isPrime to create the calculation and print out the result in main. I'm sure it's something small that I'm missing, but I can't get it to produce an accurate result.
public static void main(String[] args) {
System.out.print("Enter number: ");
int num = s.nextInt();
if (isPrime(num) == true) {
System.out.println("Number is prime");
} else if (isPrime(num) == false) {
System.out.println("Number is not prime");
}
}
public static boolean isPrime(int num){
for(int i = 2; i <= num/2; i++) {
if (num%i != 0) {
return true;
}
}
return false;
}
Use an if and else (don't retest your boolean condition in the first case). And don't test for == true in an if. This
if(isPrime(num) == true)
{
System.out.println("Number is prime");
}
else if(isPrime(num) == false)
{
System.out.println("Number is not prime");
}
Should just be
if (isPrime(num)) {
System.out.println("Number is prime");
} else {
System.out.pritnln("Number is not prime");
}
or even something like
System.out.print("Number is ");
if (!isPrime(num)) {
System.out.print("not ");
}
System.out.println("prime");
If you want to put the braces on their own lines go ahead. As for your isPrime method; you have your return conditions reversed (and the test as well). Also we can optimize it a bit. Unroll the first even test, because then we can skip every other element. Also we only need to test to the square root of the input number. Like,
public static boolean isPrime(int num) {
if (num == 2) {
return true; // two is prime.
}
if (num < 1 || num % 2 == 0) {
return false; // all other even numbers are not prime.
}
for(int i = 3; i <= Math.sqrt(num); i += 2) {
if (num % i == 0) {
return false;
}
}
return true;
}
The isPrime(int num) method may need to check if num % i == 0 instead of if num % i != 0 because many non-prime numbers will pass the condition and return true.
As an example, if isPrime(9) is called, the conditional will check if 9 % 2 != 0, which is true, and the method will say that 9 is prime when it's not.
As a result, you could try changing the method to something like this:
public static boolean isPrime(int num)
{
for(int i = 2; i <= num/2; i++)
{
if (num%i==0)
{
return false;
}
}
return true;
}
You should change your "if (num%i!=0)" condition to if(num % i == 0)
See the following code:
public class Prime {
public static void main(String[] args) {
int num = 29;
boolean flag = false;
for(int i = 2; i <= num/2; ++i)
{
// condition for nonprime number
if(num % i == 0)
{
flag = true;
break;
}
}
if (!flag)
System.out.println(num + " is a prime number.");
else
System.out.println(num + " is not a prime number.");
}
}
So my professor had us do an assignment that asks the user for 5 numbers that are valid (51-99) and unique (non-repeating). I just can't figure out why my nested for loop inside the while loop is not incrementing the i, I suspect it is the break; but without that the for loop keeps looping. Any help would be awesome. Thank you.
public static void main(String[] args) {
int[] userArray;
userArray = new int[5];
int real = 0;
System.out.println("Please print out 5 numbers between 50 and 100. ");
Scanner entry = new Scanner(System.in);
while (real < 5) {
int count = entry.nextInt();
boolean aCount = isValid(count);
if (aCount == true) {
for (int i =0; i < userArray.length; i++) {
userArray[i] = count;
real++;
break;
}
} else {
System.out.println("That is not a valid number.");
}
}
}
public static boolean isValid(int a) {
if (a > 50 && a < 100) {
return true;
} else {
return false;
}
}
I got it guys! I just had to remove the for loop and put this in:
userArray[i] = count;
i++;
real++;
Thank you schmidt73 and everyone that helped!
int i=0;
while (real < 5) {
int count = entry.nextInt();
boolean aCount = isValid(count);
if (aCount == true) {
userArray[i++] = count;
real++;
} else {
System.out.println("That is not a valid number.");
}
}
I guess this is what you are trying to do.
First, you also need to test if the array contains the value you are trying to add (in validate). You could do something like
public static boolean isValid(int[] arr, int real, int a) {
if (a > 50 && a < 100) {
for (int i = 0; i < real; i++) {
if (arr[i] == a) {
return false;
}
}
return true;
}
return false;
}
Then your main method might be written like
int[] userArray = new int[5];
int real = 0;
System.out.println("Please print out 5 numbers between 50 and 100. ");
Scanner entry = new Scanner(System.in);
while (real < 5) {
int count = entry.nextInt();
if (isValid(userArray, real, count)) {
userArray[real++] = count;
} else {
System.out.println("That is not a valid number.");
}
}
System.out.println("The array contains: " + Arrays.toString(userArray));
My program seems to work with numbers '25, 223, and 11" but i have no idea why it stops when i enter the numbers 10 or 100. Any ideas? Any help on this matter will be greatly appreciated-thank you in advance.
*****Source Code*****
import java.util.Scanner;
public class hw_5 {
public static void main(String[] args) {
Scanner inputReader = new Scanner(System.in);
int num;
boolean primeTest;
System.out.print("Enter an integer value: ");
num = inputReader.nextInt();
if(num != -1) {
primeTest = calcPrime(num);
if(!primeTest) {
System.out.println(num+" is not prime.");
printFactors(num);
}
}
}
public static boolean calcPrime(int num) {
for(int i = 2; i < num; i++) {
if(num % i == 0)
return true; // If number is divisible by any number, return true.
}
return false; // If loop exits (means, number was not divisible by any number), return false.
}
public static void printFactors(int num) {
int nFactors = 0;
for(int i = 2; i < num; i++) {
if(num % i == 0) {
System.out.println(num+" is divisible by "+i);
nFactors++;
}
}
System.out.println(num+" has "+nFactors+" factors");
}
}
import java.util.Scanner;
public class Test {
public static boolean calcPrime(int num) {
for(int i = 2; i < num; i++) {
if(num % i == 0)
return false; // If number is divisible by any number, return false.
}
return true; // If loop exits (means, number was not divisible by any number), return true.
}
public static void printFactors(int num) {
int nFactors = 0;
for(int i = 2; i < num; i++) {
if(num % i == 0) {
System.out.println(num+" is divisible by "+i);
nFactors++;
}
}
System.out.println(num+" has "+nFactors+" factors");
}
public static void main(String[] args) {
Scanner inputReader = new Scanner(System.in);
int num = 0;
boolean primeTest = false;
while(true) {
System.out.print("Enter an integer value: ");
num = inputReader.nextInt();
if(num == -1)
break;
primeTest = calcPrime(num);
if(primeTest)
System.out.println(num+" is prime.");
else {
System.out.println(num+" is not prime.");
printFactors(num);
}
}
}
}
Your prime test is wrong :
public static int calcPrime(int number) {
int primer = number % 2;
return primer;
}
It just tests if the number is odd.
Below method returns true if it is a prime number ,
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;
}
You could add the numbers to the list and get the their values on iterating back
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Please have a look at the following code
public class Prime
{
public static void main(String[]args)
{
int i = 2;
int counter = 0;
while(true)
{
if(counter==6)//Count still 6
{
break;
}
else
{
if(getPrimes(i)==true)
{
i++;
counter++;
System.out.println("Counter: "+counter);
}
else
{
System.out.println("No");
}
}
}
}
static boolean getPrimes(int num)
{
boolean result = false;
int i = 2;
while(true)
{
if((num%i) != 0) //if the number cannot be divided by any other number (except 1 and it self) it is prime
{
result = true;
System.out.println(num);
System.out.println("I is: "+i);
i=2;
break;
}
else //Not a prime. Repeat the process
{
result = false;
i++;
}
}
return result;
}
}
In here, I am trying to get all the prime numbers between 0-6. This is the test case to get thousands of prime numbers from a really big number. However, it is not showing the only primes, it is showing each and every number!
What am I doing here wrong? Please help!
try this answer...in ur loop
static boolean getPrimes(int num)
{
boolean result=true; // incase u gave 1 or 2 as input.....
int i = 2;
int mid=num/2;
while(i<mid)
{
if(num%i==0)
{
result=false; // not a prime and breaks...
break;
}
else
{
result=true; // the loop make result as true.....
}
i++;
}
return result;
}
I think you need something like this:
public void getPrimes(int a){
for(int i = 2; i < a; i++){
int inCounter = 0;
if(counter%i==0){
System.out.println("false");
inCounter++;
}
if(inCounter == 0){
System.out.println("Prime: "+counter);
}
}
}
Use a sieve, either Eratosthenes or Atkins
Here's the Eratosthenes implementation by Robert Sedgewick in Java:
http://introcs.cs.princeton.edu/java/14array/PrimeSieve.java.html
I guess I found the solution. At least, I found the answer I need. Here is my answer
import java.math.BigInteger;
public class Problem7
{
public static void main(String[]args)
{
int i = 0;
int counter = 0;
while(true)
{
if(i>6)
{
break;
}
if(i>1)
{
String str = String.valueOf(i);
if (new BigInteger(str).isProbablePrime(i/2))
{
System.out.println(str);
counter++;
}
}
i++;
}
}
}
I guess this is the easiest way...
import java.util.Scanner;
class PrimeNumbers2
{
public static void main (String[] args)
{
Scanner scanner = new Scanner(System.in);
int i =0;
int num =0;
//Empty String
String primeNumbers = "";
System.out.println("Enter the value of n:");
int n = scanner.nextInt();
for (i = 1; i <= n; i++)
{
int counter=0;
for(num =i; num>=1; num--)
{
if(i%num==0)
{
counter = counter + 1;
}
}
if (counter ==2)
{
//Appended the Prime number to the String
primeNumbers = primeNumbers + i + " ";
}
}
System.out.println("Prime numbers from 1 to n are :");
System.out.println(primeNumbers);
}
}
it will display all the prime number.
Find Prime number with minimum iteration
boolean IsPrimeNumber(int num) {
boolean isPrime = true;
if (num == 1 || num ==0)
isPrime = false;
else{
int limit = (int) Math.sqrt(num);
for (long i = 2L; i <=limit ; i++)
if (num % i == 0) {
isPrime = false;
break;
}
}
return isPrime;
}
Im new to java and I was wondering how i would print prime palindrome without using strings and only methods.
This is what I have so far. I want to print every prime palindrome number before 50. I did this with prime numbers only and it was working but when I added in palindrome, it did not work.
EDIT: i added in the int original = number like one of the answers says but my output is always 2,3,5,7,11 and nothing more.
EDIT2(1 more question): I changed the value up to 1000 and my output is 2 3 5 7 11 313 353 373 383 727 757 787 797 919 929. The output is correct but isn't 101, 131, 151, 181, 191 also prime palindrome numbers? Why are they not included in the output?
public class primePalindrome {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number");
int num = input.nextInt();
System.out.println("The prime palindrome numbers are \n");
printPP(num);
}
public static void printPP(int numberOfPP) {
final int NUMBER_OF_PP_PER_LINE = 10;
int count = 0;
int number = 2;
while (number < numberOfPP) {
if(isPrime(number) && isPalindrome(number)) {
count++;
if (count % NUMBER_OF_PP_PER_LINE ==0) {
System.out.printf("%-5s\n", number);
}
else
System.out.printf("%-5s", number);
}
number++;
}
}
public static boolean isPrime(int number) {
for (int divisor = 2; divisor <= number / 2; divisor++) {
if (number % divisor == 0) {
return false;
}
}
return true;
}
public static boolean isPalindrome(int number) {
int reverse = 0;
int n = number;
for (int i = 0; i <= number; i++) {
int remain = number%10;
number = number/10;
reverse = reverse*10+remain;
}
if (reverse == n) {
return true;
}
}
return false;
}
}
There's only one 2-digit prime palindrome: 11. Every other 2-digit number is divisible by 11. Your output is thus correct.
Your isPalindrome is quite close:
1) Move the equality check outside the loop
2) Use while-loop. Using "for" results in omitting palindrome patterns 1X1, 2XX2 etc.
3) Dont't forget to preserve the argument:
public static boolean isPalindrome(int number) {
int original = number;
int reverse = 0;
while (number > 0) {
int digit = number%10;
number = number/10;
reverse = reverse*10+remain;
}
return reverse == original;
}
You were close. At the end you compare number to reverse. Unfortunately, number has been modified. You need to compare number's original value to reverse. Here's my modified version:
public static boolean isPalindrome(int number) {
int original = number;
int reverse = 0;
for (int i = 0; i <= number; i++) {
int remain = number % 10;
number = number / 10;
reverse = reverse * 10 + remain;
}
return reverse == original;
}
/* Palindrome Program In JAVA
Credit: Code Nirvana (www.codenirvana.in)
*/
import java.util.Scanner;
class Palindrome{
public static void main(String args[]){
System.out.print("Enter Number: ");
Scanner read = new Scanner(System.in);
int num = read.nextInt();
int n = num;
//reversing number
int rev=0,rmd;
while(num > 0)
{
rmd = num % 10;
rev = rev * 10 + rmd;
num = num / 10;
}
if(rev == n)
System.out.println(n+" is a Palindrome Number!");
else
System.out.println(n+" is not a Palindrome Number!");
}
}
Since most of the answers above doesn't work for both positive and negative numbers, following is one which works for negative numbers as well.
private static boolean isPalindrome(int n) {
int orignal = n, reversed = 0;
while (n != 0) {
reversed = (reversed * 10) + (n % 10);
n /= 10;
}
return reversed == orignal;
}
What if the given input is a huge number or a string?
I believe the below code should work for any input.
private boolean isPalindrome(String s) {
int lo = 0, hi = s.length()-1;
while(lo < hi) {
if(s.charAt(lo) == s.charAt(hi)) {
lo++; hi--;
} else {
return false;
}
}
return true;
}
import java.util.Scanner;
/*if given number is same with reverse number
then this number is called as Palindrome number. */
public class PalindromeNumber {
public static void main(String args[])
{
int input,store,output=0;
Scanner in=new Scanner(System.in);
System.out.println("Enter a number for check.");
input=in.nextInt();
store=input;
while (input!=0)
{
output=output*10;
output=output+input%10;
input=input/10;
}
System.out.println(output);
if (output == store)
{
System.out.println("This is a palindrome number.");
}
else
{
System.out.println("This is not a palindrome number.");
}
in.close();
}
}
import java.util.*;
/*
# Author 12CSE54
# Date 29.10.14
*/
public class cpalindrome
{
public static void main(String ar[])throws Exception
{
Scanner s=new Scanner(System.in);
System.out.println("Enter the number\n");
int n=sc.nextInt();
int s=0,r;
while(n>0)
{
r=n%10;
s=(s*10)+r;
n/=10;
}
if(n==s)
System.out.println("palindrome\n");
else
System.out.println("not a palindrome");
}
}
import java.util.*;
public class PalPrime
{
public boolean prime(int n)
{
int c=0;
for(int i=1;i<=n;i++)
{
if(n%i==0)
c++;
}
if(c==2)
return true;
else
return false;
}
public boolean palindrome(int n)
{
int rev=0,temp=n;
while(temp!=0)
{
rev=rev*10+(temp%10);
temp=temp/10;
}
if(rev==n)
return true;
else
return false;
}
public static void main(String args[])
{
Scanner ob=new Scanner(System.in);
System.out.println("Enter number to be checked");
int num=ob.nextInt();
PalPrime obj=new PalPrime();
if(obj.prime(num)==true && obj.palindrome(num)==true)
System.out.println(num+" is a Prime Palindrome i.e. a PalPrime Number");
else
System.out.println(num+" is not a PalPrime Number");
}
}
TRY THIS!
This is easy to Understand
public class StringDemo {
public static void main(String args[]) {
if(palindrome("1211")){
System.out.println("Yes IT IS palindrome");
}
if(palindrome("121")){
System.out.println("Yes IT IS palindrome");
}
}
public static boolean palindrome(Object o){
String s=(String)o;
boolean result=true;
int temp=s.length()-1;
for(int c=0;c<temp;c++){
if(s.charAt(c)==s.charAt(temp)){
temp--;
//System.out.println("Pallidrom start "+ s.charAt(c));
//System.out.println("Pallidrom end "+ s.charAt(temp));
}else{
System.out.println("NOT palindrome");
return false;
}
}
return result;
}
}
Result is