I have written a program to find whether a number is prime or not.
The program has 2 methods:
take input from user as to the numbers(stored in an array)
take each element of the array and to find whether it is prime or not (this method return type is boolean)
Now my 2nd method is always returning true for all values.
public static boolean Isprime(int x){
boolean isprime = false;
for(int m=2;m<x/2;m++){
int temp = x%m;
if(temp == 0){
isprime = false;
}
else{
isprime = true;
}
}
return isprime;
}
Edited:
public static boolean Isprime(int x){
boolean isprime = false;
for(int m=2;m<=x/2;m++){
int temp = x%m;
if(temp == 0){
isprime = false;
break;
}
else{
isprime = true;
}
}
return isprime;
}
P.S - It is working for 9 as well.
You need to break out of for loop as soon as you found if it is not a prime and slighlty modified approach you can follow to omit some code and optimize it as well.
public static boolean Isprime(int x){
boolean isprime = true;
for(int m=2;m<=Math.sqrt(x);m++){
int temp = x%m;
if(temp == 0){
isprime = false;
break;
}
}
return isprime;
}
Related
I am trying to find palindrome no but every time it is showing false for every no even for 121
please Help....
public boolean isPalindrome(int x) {
if(x<0 || x%10==0){
return false;
}
int rev = 0;
while(x!=0){
rev=(rev*10)+(x%10);
x/=10;
}
if(x==rev){
return true;
}
else{
return false;
}
}
enter image description here
As an option, you may create something like this:
public boolean isPalindrome(int x) {
StringBuilder sb = new StringBuilder();
sb.append(x);
return sb.toString().equals(sb.reverse().toString());
}
Because after your while loop ends, x will be 0, you have to act on a copy instead
public boolean isPalindrome(int x) {
int num = x;
if(x<0 || x%10==0){
return false;
}
int rev = 0;
while(x!=0){
rev=(rev*10)+(x%10);
x/=10;
}
if(num==rev){
return true;
}
else{
return false;
}
}
All you need to do is build the new number as you reduce the original. Then compare the two.
for (int i : new int[]{121,12321, 123,34543,20012}) {
System.out.printf("%6d - %s%n", i, isPalindrome(i));
}
public static boolean isPalindrome(int numb) {
int n = 0;
for (int b = numb; b > 0;) {
n *= 10;
n += b%10;
b/=10;
}
return n == numb;
}
Prints
121 - true
12321 - true
123 - false
34543 - true
20012 - false
Hope this is useful:
public static boolean palindrome(int n) {
int nPalindrome = 0;
int nCopy = n;
while (n != 0) {
nPalindrome = nPalindrome *10 + n % 10;
n = n / 10;
}
if (nCopy == nPalindrom) {
return true;
} else {
return false;
}
}
You function can be as simple as below
public static void main(String args[]){
int r,sum=0;
int n=454;//It is the number variable to be checked for palindrome
if(isPalindrome(n)) {
System.out.println("palindrome number ");
} else {
System.out.println("not palindrome number ");
}
}
public boolean isPalindrome(int n) {
while(n>0){
r=n%10; //getting remainder
sum=(sum*10)+r;
n=n/10;
}
return n==sum;
}
I'm trying to find out if a number is a prime number or not. I created this method, which I will be using in another class later.
When compiling it tells me that I need a return statement outside the for-loop, but if I try to return the boolean value it gives me an error (cannot find symbol). What shall I return?
public class NumeroPrimo {
public static boolean primo(int numero){
for (int i=2; i<numero/2; i++){
if(numero%i==0){
return false;
}
else return true;
}
}
}
If the loop was not done (numero 1), no return would happen.
Also you return true too often.
public static boolean primo(int numero) {
for (int i = 2; i <= numero/2; i++) {
if (numero % i == 0){
return false;
}
}
return true;
}
Also for 4 <= is required.
static boolean isPrime(int num){
int consNum = num; //something like having a non-changing value
if(consNum < 2){
return false;
}
else if( consNum % Math.round(num--/2) == 0 && num > 2)
return false;
}
else{
if(num==1)
return true;
else
return isPrime(num);
}
}
I'm trying to create a function that will determine if num is a prime number. Problem, i want a value(consNum) to stay with that value during the first call, Is there a way to do this recursively?
Edit
from:
if( (consNum % (int)(num--/2) + 0.5 == 0 )
to:
if( (consNum % Math.round(num--/2) == 0 && num > 2)
Local variables are local to the invocation of the particular method;
recursive methods are no exception.
If you wish to pass that value down the invocation chain, you need to make a second parameter for it, and pass it down explicitly:
// Users of your code invoke this method
public static boolean isPrime(int num) {
return isPrime(num, num);
}
// This overload with two parameters is the actual recursive method
private static boolean isPrime(int num, int original) {
if(original%(int)((num--/2)+0.5)==0)
return false;
}
else{
if(num==1)
return true;
else
return isPrime(num, original);
}
}
Try this
static boolean isFirst=true;
static int consNum;
static boolean isPrime(int num){
if(isFirst){ // This condition will help you to keep consNum with the initial value
consNum=num;
isFirst=false;
}
if(consNum%(int)((num--/2)+0.5)==0)
return false;
}
else{
if(num==1)
return true;
else
return isPrime(num);
}
}
I have to do the method, that I give a number in, if it is a Square number, it will get me true back
if it's not it will get me false back,
I wrote the code:
public class Aufgabe {
static boolean x;
public static boolean istQuadratzahl(int zahl){
int n = (int) Math.sqrt(zahl);
if (zahl%n == 0){
x = true;
}
else {
return x=false;
}
return x;
}
public static void main(String []args){
System.out.println(istQuadratzahl(6));
}
}
but when I give 6 or 8 in, it gives me true back, where did I go wonge here?
In your case, sqrt(6) is 2.44948974278. When you cast it to int it becomes 2. Of course, 6 % 2 = 0.
Try to check the result with:
if (zahl == n * n){
x = true;
}
This will do the trick:
public boolean isSquare(double zahl){
double m=Math.sqrt(zahl);
double n=(int)Math.sqrt(zahl);
if(m==n)
return true;
else
return false;
}
int sqrt = (int) Math.sqrt(inputNumber);
if(sqrt*sqrt == number) {
System.out.println(number+" is a perfect square number!");
return true;
}else {
System.out.println(number+" is NOT a perfect square number!");
return false;
}
Don't use a static variable. In fact, don't use a variable at all.
In addition, your logic is wrong. (int)Math.sqrt(12) == 3, 12%3 == 0, but 12 is not a square.
public static boolean istQuadratzahl(int zahl)
{
int n = (int) Math.sqrt(zahl);
if (n*n == zahl)
return true;
else
return false;
}
change the 'if' to this
if (zahl == n * n){
So I have the majority of the code written and it works. Except for the iterative method keeps showing that it is not a palindrome regardless of what is typed in. I am at a loss as to how to remedy it here is the code.
//David Crouse Assignment 2
import java.util.Scanner;
public class Assignment2 {
public static boolean loop = false;
//main
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Palindrome Checker!");
do{
System.out.print("Enter a string to check if it is a palindrome. ");
System.out.print("Enter x to exit.");
String word = input.nextLine();
word = word.replaceAll("\\s","");
word = word.toLowerCase();
//Exit Program
if(word.equalsIgnoreCase("x")){
System.out.println("End of program. Good Bye!");
System.exit(0);
}
if(iterativePalindromeChecker(word)){
System.out.println("Iterative Result: Palindrome!");
}else{
System.out.println("Iterative Result: Not a palindrome");
}
if(recursivePalindromeChecker(word)){
System.out.println("Recursive Result: Palindrome!\n");
}else{
System.out.println("Recursive Result: Not a palindrome\n");
}
loop = true;
}while (loop == true);
}
//Iterative Method
public static boolean iterativePalindromeChecker(String str){
boolean result = false;
int length = str.length();
int i, begin, end, middle;
begin = 0;
end = length - 1;
middle = (begin + end)/2;
for (i = begin; i <= middle; i++) {
if (str.charAt(begin) == str.charAt(end)) {
begin++;
end--;
}
else {
break;
}
}
if (i == middle + 1) {
result = false;
}
return result;
}
//Recusive Methods
public static boolean recursivePalindromeChecker(String str){
if(str.length() == 0 || str.length() == 1)
return true;
if(str.charAt(0) == str.charAt(str.length()-1))
return recursivePalindromeChecker(str.substring(1,str.length()-1));
return false;
}
}
Your iterative method never sets result to be true. Here's a modified version:
public static boolean iterativePalindromeChecker(String str){
int length = str.length();
int i, begin, end, middle;
begin = 0;
end = length - 1;
middle = (begin + end)/2;
for (i = begin; i <= middle; i++) {
if (str.charAt(begin) == str.charAt(end)) {
begin++;
end--;
}
else {
return false;
}
}
return true;
}
Your iterative method does not set result = true anywhere, so it really can't help it. Although I think the iterative method could be better overall. Take a close look at what is happening in the recursive one and see if you can implement some of it (like the guard conditions) more closely in the iterative method, and keep in mind that you are not limited to a single index value in a for loop either. e.g.:
public static boolean iterativePalindromeChecker(String str) {
for(int start = 0, end = str.length() - 1; start < end; start++, end--) {
if(str.charAt(start) != str.charAt(end)) {
return false;
}
}
return true;
}
I'm guessing someone once told you that a function should only have one return point, and trying to follow that led you to using a mutable result variable which screwed you here. Using break poses the same ostensible problem anyway. Save yourself the headache and just return as soon as you know the answer.
public static boolean iterativePalindromeChecker(String str) {
int begin = 0;
int end = str.length() - 1;
while (begin < end) {
if (str.charAt(begin) != str.charAt(end)) {
return false;
}
begin++;
end--;
}
return true;
}