Java program not outputting correct values - java

I'm trying to create a simple program that determines if a number can be written as n^x and what n and x are. Ex: 81 = 3^4. My program correctly identifies numbers that can be written as n^x but the values for n and x are way off. (this is just supposed to be an exercise). The logic in my coding is kind of confusing so here's basically what it is. First it finds a number that can divide into a (the chosen number), then it figures out if the a can be divided by the number until it reaches 1. Then it figures out how many times it takes to reach 1. I can't find any problems with the logic. Here's my code.
public static void main(String[] args) {
Scanner scan1 = new Scanner(System.in);
int a = scan1.nextInt();
scan1.close();
int i = 2;
boolean y = false;
int x = 0;
for (; i <= Math.sqrt(a); i++) {
if (a % i == 0) {
int n = i;
for (; n <= a; n *= i) {
if (a % n != 0) {
y = false;
break;
}
x++;
y = true;
}
}
}
if (y == true) {
System.out.println(a + " = " + i + " ^ " + x);
}
else {
System.out.println("Your number cannot be represented as n^x");
}
}

public static void main(String[] args) {
Scanner scan1 = new Scanner(System.in);
int a = scan1.nextInt();
scan1.close();
int i = 2;
boolean y = false;
int x = 0;
for(; i <= Math.sqrt(a); i++) {
if (a % i == 0) {
int n = i;
for (; n <= a; n *= i) {
if (a % n != 0) {
y = false;
}
y = true;
x = n;
break;
}
}
}
i--;
if (y == true) {
System.out.println(a + " = " + i + " ^ " + x);
}
else {
System.out.println("Your number cannot be represented as n^x");
}
}
Use a do-while for the outer loop and you won't need i--; at the end.

Related

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

How would I speed up this program?

I am currently attempting to solve a ProjectEuler problem and I have got everything down, except the speed. I am almost certain the reason the program executes so slowly is due to the nested loops. I would love some advice on how to speed this up. I am a novice programmer, so I am not familiar with a lot of the more advanced methods/topics.
public class Problem12 {
public static void main(String[] args) {
int num;
for (int i = 1; i < 15000; i++) {
num = i * (i + 1) / 2;
int counter = 0;
for (int x = 1; x <= num; x++) {
if (num % x == 0) {
counter++;
}
}
System.out.println("[" + i + "] - " + num + " is divisible by " + counter + " numbers.");
}
}
}
EDIT : Below is the new code that is exponentially faster. Removed the constant line printing as well to speed it up even more.
public class Problem12 {
public static void main(String[] args) {
int num;
outerloop:
for (int i = 1; i < 25000; i++) {
num = i * (i + 1) / 2;
int counter = 0;
double root = Math.sqrt(num);
for (int x = 1; x < root; x++) {
if (num % x == 0) {
counter += 2;
if (counter >= 500) {
System.out.println("[" + i + "] - " + num + " is divisible by " + counter + " numbers.");
break outerloop;
}
}
}
}
}
}
For starters, when looking at divisors, you never need to go further than the root square of the number, because each divisor below the square root has an equivalent above.
n = a * b => a <= sqrt(n) or b <= sqrt(n)
Then you need to count the other side of the division:
double root = Math.sqrt(num);
for (int x = 1; x < root; x++) {
if (num % x == 0) {
counter += 2;
}
}
The square root is special because it counts only once if it is integer:
if ((double) ((int) root) == root) {
counter += 1;
}
You just need to factorize the number. p^a * q^b * r^c has (a+1)*(b+1)*(c+1) divisors. Here is some basic implementation using this idea:
static int Divisors(int num) {
if (num == 1) {
return 1;
}
int root = (int) Math.sqrt(num);
for (int x = 2; x <= root; x++) {
if (num % x == 0) {
int c = 0;
do {
++c;
num /= x;
} while (num % x == 0);
return (c + 1) * Divisors(num);
}
}
return 2;
}
public static void test500() {
int i = 1, num = 1;
while (Divisors(num) <= 500) {
num += ++i;
}
System.out.println("\nFound: [" + i + "] - " + num);
}

replacing a string in an array and keeping it in memory?

so im having problems polishing up my program. this program is supposed to create a 1D array with a user input. then it creates a box of 'O's like this..
N = 4
OOOO
OOOO
OOOO
OOOO
the user inputs coordinates based on the box and the 'O' is changed to an 'X'.
the program is supposed to repeat itself after the coordinates are selected while remembering the position of X and including it in the next loop.
i tried implementing a while loop but it seems that code just loops over the Array without remembering the last position of X.
how could i change the code so it does what i need it to do?
public static void makeArray(int M) {
String input = "";
boolean repeat = false;
int N = InputNumber(input);
String[] Board = new String[N];
M = (int) Math.sqrt(N);
String A = "O";
String B = "X";
System.out.println("Printing " + (M) + " x " + (M) + " board...");
System.out.println("Done.");
System.out.println();
while (!repeat) {
int X = Xvalue(M);
int Y = Yvalue(M);
int C = convertIndex(X, Y, M);
System.out.println("Marking location " + X + "," + Y + ")");
for (int i = 0; i < (Board.length); i++) {
{
Board[i] = A;
if ((i % M == 0)) {
System.out.println();
}
if (i == C) {
Board[i] = Board[i].replace(A, B);
}
if (i == C && C == -1) {
repeat = true;
}
}
System.out.print(Board[i]);
}
System.out.println();
}
}
public static int convertIndex(int x, int y, int N) {
int valX = (x - 1) * N;
int valY = y;
int targetIndex = valX + valY;
return (targetIndex - 1);
}
public static int Xvalue(int M) {
boolean repeat = false;
int X = 0;
while (!repeat) {
System.out.print("Please enter the X-coordinate: ");
String InputX = new Scanner(System.in).nextLine();
X = Integer.parseInt(InputX);
if (X > M) {
System.out.println();
System.out.println("Error, please enter a valid X Coordinate...");
repeat = false;
} else {
repeat = true;
}
}
return X;
}
public static int Yvalue(int M) {
boolean repeat = false;
int Y = 0;
while (!repeat) {
System.out.println();
System.out.print("Please enter the Y-coordinate: ");
String InputY = new Scanner(System.in).nextLine();
Y = Integer.parseInt(InputY);
if (Y > M) {
System.out.println("Error, please enter a valid Y Coordinate...");
repeat = false;
} else {
repeat = true;
}
}
return Y;
}
The trouble with you loop is that it defines every element in you your array before it prints them:
while (!repeat) {
//...
for (int i = 0; i < (Board.length); i++) {
{
Board[i] = A; //Makes each element "O"
//...
if (i == C) { //Makes only the current cooridinate "X"
Board[i] = Board[i].replace(A, B);
}
//...
}
System.out.print(Board[i]);
}
}
To fix it so that old X's are retained, you need to remove assignment Board[i] = A;. But you'll still need to initialize your board, or else you'll have null strings. So you need to add something before the loop like:
String[] Board = new String[N];
M = (int) Math.sqrt(N);
String A = "O";
String B = "X";
//initialize board
for (int i = 0; i < Board.length; i++)
Board[i] = A;
Try using a char[][] instead of a String[]. Then you can just plugin the coordinates the user inputs (e.g. board[x][y] = B). This better represents what you're showing the user as well.
This saves you from having to loop through your String[] and then finding the right character to change. Remember, Strings are immutable, so you'd have to reassign the entire string after replacing the right character. With the char[][] you simply assign 'X' to the right coordinates.
EDIT:
Since a single array is required, you should be able to do the following (instead of looping):
board[x] = board[x].substring(0, y) + A + board[x].substring(y + 1);

Can't figure out the error Luhn check

Its supose to tell me if a card is valid or invalid using luhn check
4388576018402626 invalid
4388576018410707 valid
but it keeps telling me that everything is invalid :/
Any tips on what to do, or where to look, would be amazing. I have been stuck for a few hours.
It would also help if people tell me any tips on how to find why a code is not working as intended.
im using eclipse and java
public class Task11 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a credit card number as a long integer: ");
long number = input.nextLong();
if (isValid(number)) {
System.out.println(number + " is valid");
} else {
System.out.println(number + " is invalid");
}
}
public static boolean isValid(long number) {
return (getSize(number) >= 13) && (getSize(number) <= 16)
&& (prefixMatched(number, 4) || prefixMatched(number, 5) || prefixMatched(number, 6) || prefixMatched(number, 37))
&& (sumOfDoubleEvenPlace(number) + sumOfOddPlace(number)) % 10 == 0;
}
public static int sumOfDoubleEvenPlace(long number) {
int result = 0;
long start = 0;
String digits = Long.toString(number);
if ((digits.length() % 2) == 0) {
start = digits.length() - 1;
} else {
start = digits.length() - 2;
}
while (start != 0) {
result += (int) ((((start % 10) * 2) % 10) + (((start % 10) * 2) / 2));
start = start / 100;
}
return result;
}
public static int getDigit(int number) {
return number % 10 + (number / 10);
}
public static int sumOfOddPlace(long number) {
int result = 0;
while (number != 0) {
result += (int) (number % 10);
number = number / 100;
}
return result;
}
public static boolean prefixMatched(long number, int d) {
return getPrefix(number, getSize(d)) == d;
}
public static int getSize(long d) {
int numberOfDigits = 0;
String sizeString = Long.toString(d);
numberOfDigits = sizeString.length();
return numberOfDigits;
}
public static long getPrefix(long number, int k) {
String size = Long.toString(number);
if (size.length() <= k) {
return number;
} else {
return Long.parseLong(size.substring(0, k));
}
}
}
You should modiffy your isValid() method to write down when it doesn't work, like this:
public static boolean isValid(long number) {
System.err.println();
if(getSize(number) < 13){
System.out.println("Err: Number "+number+" is too short");
return false;
} else if (getSize(number) > 16){
public static boolean isValid(long number) {
System.err.println();
if(getSize(number) < 13){
System.out.println("Err: Number "+number+" is too short");
return false;
} else if (getSize(number) > 16){
System.out.println("Err: Number "+number+" is too long");
return false;
} else if (! (prefixMatched(number, 4) || prefixMatched(number, 5) || prefixMatched(number, 6) || prefixMatched(number, 37)) ){
System.out.println("Err: Number "+number+" prefix doesn't match");
return false;
} else if( (sumOfDoubleEvenPlace(number) + sumOfOddPlace(number)) % 10 != 0){
System.out.println("Err: Number "+number+" doesn't have sum of odd and evens % 10. ");
return false;
}
return true;
}
My guess for your problem is on the getPrefix() method, you should add some logs here too.
EDIT: so, got more time to help you (don't know if it's still necessary but anyway). Also, I corrected the method I wrote, there were some errors (like, the opposite of getSize(number) >= 13 is getSize(number) < 13)...
First it will be faster to test with a set of data instead of entering the values each time yourself (add the values you want to check):
public static void main(String[] args) {
long[] luhnCheckSet = {
0, // too short
1111111111111111111L, // too long (19)
222222222222222l // prefix doesn't match
4388576018402626l, // should work ?
};
//System.out.print("Enter a credit card number as a long integer: ");
//long number = input.nextLong();
for(long number : luhnCheckSet){
System.out.println("Checking number: "+number);
if (isValid(number)) {
System.out.println(number + " is valid");
} else {
System.out.println(number + " is invalid");
}
System.out.println("-");
}
}
I don't know the details of this, but I think you should work with String all along, and parse to long only if needed (if number is more than 19 characters, it might not parse it long).
Still, going with longs.
I detailed your getPrefix() with more logs AND put the d in parameter in long (it's good habit to be carefull what primitive types you compare):
public static boolean prefixMatched(long number, long d) {
int prefixSize = getSize(d);
long numberPrefix = getPrefix(number, prefixSize);
System.out.println("Testing prefix of size "+prefixSize+" from number: "+number+". Prefix is: "+numberPrefix+", should be:"+d+", are they equals ? "+(numberPrefix == d));
return numberPrefix == d;
}
Still don't know what's wrong with this code, but it looks like it comes from the last test:
I didn't do it but you should make one method from sumOfDoubleEvenPlace(number) + sumOfOddPlace(number)) % 10 and log both numbers and the sum (like i did in prefixMatched() ). Add logs in both method to be sure it gets the result you want/ works like it should.
Have you used a debugger ? if you can, do it, it can be faster than adding a lot of logs !
Good luck
EDIT:
Here are the working functions and below I provided a shorter, more efficient solution too:
public class CreditCardValidation {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int count = 0;
long array[] = new long [16];
do
{
count = 0;
array = new long [16];
System.out.print("Enter your Credit Card Number : ");
long number = in.nextLong();
for (int i = 0; number != 0; i++) {
array[i] = number % 10;
number = number / 10;
count++;
}
}
while(count < 13);
if ((array[count - 1] == 4) || (array[count - 1] == 5) || (array[count- 1] == 3 && array[count - 2] == 7)){
if (isValid(array) == true) {
System.out.println("\n The Credit Card Number is Valid. ");
} else {
System.out.println("\n The Credit Card Number is Invalid. ");
}
} else{
System.out.println("\n The Credit Card Number is Invalid. ");
}
in.close();
}
public static boolean isValid(long[] array) {
int total = sumOfDoubleEvenPlace(array) + sumOfOddPlace(array);
if ((total % 10 == 0)) {
for (int i=0; i< array.length; i++){
System.out.println(array[i]);}
return true;
} else {
for (int i=0; i< array.length; i++){
System.out.println(array[i]);}
return false;
}
}
public static int getDigit(int number) {
if (number <= 9) {
return number;
} else {
int firstDigit = number % 10;
int secondDigit = (int) (number / 10);
return firstDigit + secondDigit;
}
}
public static int sumOfOddPlace(long[] array) {
int result = 0;
for (int i=0; i< array.length; i++)
{
while (array[i] > 0) {
result += (int) (array[i] % 10);
array[i] = array[i] / 100;
}
}
System.out.println("\n The sum of odd place is " + result);
return result;
}
public static int sumOfDoubleEvenPlace(long[] array) {
int result = 0;
long temp = 0;
for (int i=0; i< array.length; i++){
while (array[i] > 0) {
temp = array[i] % 100;
result += getDigit((int) (temp / 10) * 2);
array[i] = array[i] / 100;
}
}
System.out.println("\n The sum of double even place is " + result);
return result;
}
}
I also found a solution with less lines of logic. I know you're probably searching for an OO approach with functions, building from this could be of some help.
Similar question regarding error in Luhn algorithm logic:
Check Credit Card Validity using Luhn Algorithm
Link to shorter solution:
https://code.google.com/p/gnuc-credit-card-checker/source/browse/trunk/CCCheckerPro/src/com/gnuc/java/ccc/Luhn.java
And here I tested the solution with real CC numbers:
public class CreditCardValidation{
public static boolean Check(String ccNumber)
{
int sum = 0;
boolean alternate = false;
for (int i = ccNumber.length() - 1; i >= 0; i--)
{
int n = Integer.parseInt(ccNumber.substring(i, i + 1));
if (alternate)
{
n *= 2;
if (n > 9)
{
n = (n % 10) + 1;
}
}
sum += n;
alternate = !alternate;
}
return (sum % 10 == 0);
}
public static void main(String[] args){
//String num = "REPLACE WITH VALID NUMBER"; //Valid
String num = REPLACE WITH INVALID NUMBER; //Invalid
num = num.trim();
if(Check(num)){
System.out.println("Valid");
}
else
System.out.println("Invalid");
//Check();
}
}

Why is my method repeating when I run

public class PalindromicPrimes {
public static void main (String[] args) {
userInt();
System.out.println("The palindromic primes less than " + userInt() +
" are:");
for (int i = 0; i <= userInt(); i++) {
if (isPrime() && isPalindrome()) {
System.out.println(i);
}
}
}
private static boolean isPrime() {
if (userInt() == 2 || userInt() == 3) {
return true;
}
if (userInt() % 2 == 0) {
return false;
}
int sqrt = (int) Math.sqrt(userInt()) + 1;
for (int i = 3; i < sqrt; i += 2) {
if (userInt() % i == 0) {
return false;
}
}
return true;
}
private static boolean isPalindrome() {
if (userInt() < 0)
return false;
int div = 1;
while (userInt() / div >= 10) {
div *= 10;
}
while (userInt() != 0) {
int x = userInt();
int l = x / div;
int r = x % 10;
if (l != r)
return false;
x = (x % div) / 10;
div /= 100;
}
return true;
}
private static int userInt() {
Scanner s = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int userInt = s.nextInt();
return userInt;
}
}
is there a different way of getting the user input? or can I keep it this way?
when it runs it just keeps prompting the user input.
rearrange it like this:
public static void main (String[] args) {
//get it and save it here!
int userValue = userInt();
System.out.println("The palindromic primes less than " + userValue +
" are:");
for (int i = 0; i <= userValue; i++) {
if (isPrime(userValue) && isPalindrome(userValue)) {
System.out.println(i);
}
}
}
then also update all the methods that care about this "userInt" value.
Every time you call userInt() you're telling the code to get a new value from the command line.
Try this:
public static void main (String[] args) {
int value = userInt();
System.out.println("The palindromic primes less than " + value +
" are:");
for (int i = 0; i <= value; i++) {
if (isPrime() && isPalindrome()) {
System.out.println(i);
}
}
}
The term userInt() is a function invocation that prompts the user for input. Odds are you only want to do this once. You're doing it multiple times.
You should store the result of userInt() in a variable.
int typed = userInt();
And then use this variable to reference what the user typed instead of calling userInt() again.
System.out.println("The palindromic primes less than " + typed +
" are:");
for(int i = 0; i < typed; i++) ...
You keep calling userInt(). That is the problem.
I don't understand your logic. So I have not modified that code. But the code runs.
import java.util.Scanner;
public class PalindromicPrimes {
public static void main (String[] args) {
int x = userInt();
System.out.println("The palindromic primes less than " + x +
" are:");
for (int i = 0; i <= x; i++) {
if (isPrime(i) && isPalindrome(i)) {
System.out.println(i);
}
}
}
private static boolean isPrime(int a) {
if (a == 2 || a == 3) {
return true;
}
if (a % 2 == 0) {
return false;
}
int sqrt = (int) Math.sqrt(a) + 1;
for (int i = 3; i < sqrt; i += 2) {
if (a % i == 0) {
return false;
}
}
return true;
}
private static boolean isPalindrome(int a) {
if (a < 0)
return false;
int div = 1;
while (a / div >= 10) {
div *= 10;
}
while (a != 0) {
int x = a;
int l = x / div;
int r = x % 10;
if (l != r)
return false;
x = (x % div) / 10;
div /= 100;
}
return true;
}
private static int userInt() {
Scanner s = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int userInteger = s.nextInt();
return userInteger;
}
}
Remember, don't use the same names for variable and function. In the function userInt(), you have used a variable int userInt, to get the result from the scanner. This might be aa recursive call sometimes. Be careful with that.

Categories