Trying to find largest palindrome, variable not updated [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
So I'm trying to find the largest product of 2 3-digit numbers that is a palindrome. Here's my code:
class project_euler4 {
public static int largest_palindrome = 0;
public static boolean isPalindrome(int number) {
String original = Integer.toString(number);
String reversed = new StringBuffer(original).reverse().toString();
return (original == reversed) ? true : false;
}
public static void main(String[] args) {
for (int i = 100; i < 1000; i++) {
for (int j = 100; j < 1000; j++) {
int candidate = i * j;
if (isPalindrome(candidate) && candidate > largest_palindrome) {
largest_palindrome = candidate;
}
}
}
System.out.println("The largest palindrome made from the product of 2 3-digit numbers is " + largest_palindrome);
}
}
When I compile and run, I get:
The largest palindrome made from the product of 2 3-digit numbers is 0
So for some reason, my largest_palindrome variable isn't getting updated when a product is a palindrome. I suspect it has something to do with my isPalindrome() function, but am not sure.
Any ideas?
Thanks for the help,
Mariogs

You used == instead of .equals() to compare the strings. Classic mistake.

Related

Writing a java program to find the sum of the series, 1 - 1/1! +2/2! - 3/3!... till n terms [duplicate]

This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed last year.
I want to find the sum using basic loops, so I used the following code:
// sum of first n terms in the series, 1 - 1/1! + 2/2! - 3/3!...
package assignment02;
import java.util.Scanner;
public class P7Bnew {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.println("Enter number of terms.");
int n = in.nextInt();
// using for loop to find sum
double sum =1;
for (int i =1; i<n ; i++)
{
int fact = 1;
for (int j=1; j<=i; j++)
{
fact *= i;
}
if (i%2==0)
sum+= ((int)i/fact);
else
sum -= ((int)i/fact);
}
System.out.println("The sum of first "+n+ " terms is "+sum);
}
}
I want to restrict from using the predefined functions.
In this way I am getting sum as 1 for n>=4.
So I tried another way for alternately adding and subtracting terms from :
import java.util.*;
import java.lang.*;
import java.io.*;
class P7B
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner in = new Scanner (System.in);
int a = in.nextInt();
double sum = 1;
for (int i=1; i<a ; i++)
{
int fact=1;
for (int j=2; j<=i;j++)
{
fact = fact * j;
}
int sign;
if ((i%2)==0)
sign =1;
else
sign = -1;
sum = (sum + (sign*(i/fact)));
}
System.out.println("The sum of the first "+a+ " terms of the series 1 - (1/1!) + (2/2!) - (3/3!)... is "+(sum)+".");
}
}
But I got same results.
Later when I used Math.pow(-1, i) instead of the sign variable, it gave me the correct result.
Please tell me the reason my initial attempts were giving incorrect sum for n>=4.
Your problem is that in i/fact as well as in (sign*i)/fact all operands are ints and thus you will get 0 as the result of that calculation (1/2 etc. is 0 in integer math and so will be i/i! with the exception of 1/1!and 2/2! because that's just 1/1 and 2/2). When using Math.pow(-1,i) you get a double and now the calculation works.
So to fix your code use a cast to double:
if (i%2==0)
sum += (double)i/fact;
else
sum -= (double)i/fact;

Mistake in code.What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? [closed]

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 6 years ago.
Improve this question
Hello I am doing a Euler Project :
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
But I cant't see what is wrong in my code.
Please help.
public long mainNumber()
{
long number=1;
for(int i=2;i<=20;)
{
while(number%i!=0)
{
number++;
}
i++;
}
return number;
}
public static void main(String[] args)
{
Smallest_multiple result =new Smallest_multiple();
System.out.println("The smalest multiple "+result.mainNumber());
}
Try:
public long mainNumber() {
long number = 1;
for (int i = 1; i <= 20; i++) {
if (number % i != 0) {
i = 1; //restart i
number++;
}
}
return number;
}
This will loop from 1 through 20, each time checking if i divides number evenly. If it doesn't then it sets i back to 1 and tries the next number. Of course, there's much more elegant ways of getting to this. But just I'll keep it in the iterative fashion that was presented in the post. Running this results in 232792560 as the final outcome.
Your number is almost always going to be divisible by i, after one increment of number i.e. as you increase number, it becomes divisible by the current value of i, so it will simply stop at 20, as that's the last number you're checking that it's divisible by. It needs to be divisible by ALL of them simultaneously. That's where you've gone wrong here. You simply need to keep incrementing the number and check that it's divisible by all of the numbers from 1 to 20. And once it does, then you've got your desired number. But be careful of variable type limits as you keep incrementing.
It's really not a difficult algorithm. Here's a very simple implementation of it...
public class Test {
public static void main(String[] args) {
long number = 0;
int factors = Integer.parseInt(args[0]);
boolean found = false;
while (!found) {
number++; // OR you could use [number += 2;] instead, as we know it will be even. Performance improvement! :)
found = true;
for (int i = 2; i <= factors; i++) {
found = found && number % i == 0;
}
}
System.out.println("Number: " + number);
}
}
I've written this console app to allow you to enter the number of factors you wish to check. Usage: java Test 20 to get the value you desire of 232792560.
The problem is that your outer loop may get completely exhausted and you still might not find the number that you are looking for.
You should be doing something like this:
private static long gcd(long a, long b)
{
while (b > 0)
{
long temp = b;
b = a % b;
a = temp;
}
return a;
}
public static long mainNumber()
{
long number = 1;
for(int i = 2; i <= 20; i++) {
number = number * (i / gcd(number, i));
}
return number;
}
public static void main(String[] args)
{
Smallest_multiple result =new Smallest_multiple();
System.out.println("The Smallest Multiple: " + result.mainNumber());
}
Output:
The Smallest Multiple: 232792560
Your current algorithm will fail for the large numbers but still if you want to give it a try then you can do something like this:
public long mainNumber()
{
long number = 3;
while(true)
{
boolean flag = true;
for(int i = 2; i <= 10; i++) {
if(number % i != 0) {
flag = false;
break;
}
}
if(flag) break;
else number++;
}
return number;
}
public static void main(String[] args)
{
Smallest_multiple result =new Smallest_multiple();
System.out.println("The Smallest Multiple: " + result.mainNumber());
}
Note that here I'm calculating the result for 10 and not 20. You can modify the condition in the loop as you desire.
Output:
The Smallest Multiple: 2520
Warning: You need to choose the data type carefully as it might overflow for bigger numbers.

Reverse integers in Java [duplicate]

This question already has answers here:
Java reverse an int value without using array
(33 answers)
Closed 7 years ago.
Below is a code that I have for flipping a given integer and displaying the flipped results. It runs but I have issues for when the number is smaller than two digits. It obviously cannot be flipped. I wanted to make the loop an if else stating "if number is two digits or more reverse." "Else state that the integer needs to be two or more digits." how could I go about this?
import java.util.Scanner;
public class ReverseInteger {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer that you would like to have reversed: ");
int number = input.nextInt();
reverse(number);
}
public static void reverse(int userInteger)
{
int tempDigit = 0;
while (userInteger > 0){
tempDigit = userInteger % 10;
System.out.print(tempDigit);
userInteger = userInteger / 10;
}
}
}
I am trying to get it to understand that 01 can be converted to 10. This would need to be done by the code understanding that the userInteger is more than one digit but I cant seem to figure out how to do that... Any ideas on how I can get this to check for two digits and execute the loop accordingly would be appreciated!
public static void reverse(int n)
{
int temp = 0;
int count = 0;
while(n != 0)
{
if(n%10 == 0)count++;
temp = temp*10 + n %10;
n /= 10;
}
for(int i = 0; i < count; i++)
{
System.out.print(0);
}
System.out.println(temp);
}
Convert the int to a String using Integer.toString method and save it to a string. Declare a String that will be later used as output. Start a for loop that goes through the number ( which was converted to a String) from its end to its beginning. It add each character from end to start to the output String. This results in the output String to be the reverse of the number String. Then just simply convert the output String using Integer.parseInt method and return the int value.
The code should look like:
public static int reverse(int n)
{
String number = Integer.toString(n);
String output;
for(int i = number.length()-1; i >= 0; i--)
output += number.charAt(i);
return Integer.parseInt(output);
}
I recommend using String.valueof(int).toCharArray(); and looping through in reverse to compose a new char[]. Then use Integer.parseInt(String);

Java formula for if using

I have a code and I know that it isn't right. My task is "print all two-digit numbers which don't have two equal numbers". That means - program need to print numbers like 10, 12, 13 etc. Program didnt need to print 11 because there are 2 equal numbers. Hope that my program at least some is correct. (And sorry for my english).
public class k_darbs1 {
public static void main(String[] args) {
int a,b;
boolean notequal;
for(a = 10; a < 100; a++)
{
notequal = true;
for(b = 100; b < a; b++)
{
if(a != b)
{
notequal = false;
}
}
if(notequal == true)
{
System.out.println(a);
}
}
}
}
so why making things to much complex!?!!?!!!??
public static void main(String[] args) {
for(a = 10; a < 100; a++)
{
if(a%11==0){continue;}
System.out.println(a);
}
}
I think your making this slightly more complicated than it has to be. If n is a 2-digit number, then the leading digit is n/10 (integer division by 10) and the trailing digit is n%10 (modulo 10). You can just test if those two are unequal and print n as appropriate, there's no need for another for-loop.
For instance:
int n = 42;
System.out.println(n/10);
System.out.println(n%10);
4
2
Convert it to a string and check the characters.
for (int a = 10; a < 100; a++) {
String value = String.valueOf(a);
if (value.charAt(0) != value.charAt(1)) {
System.out.println(value);
}
}
You can parse Integer to String. Then compare the numbers with substring. For this process,
you need to know
Integer.toString(i);.
string.substring();
methods. This is not a very efficent way but it is a solution.

Project Euler #10, java [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Project Euler, Problem 10 java solution not working
So, I'm attempting to solve Project Euler Problem 10 in Java, and I'm getting not the right answer. Here's my code:
public class Problem10 {
public static void main(String[] args)
{
long sum =0;
for(int i =3;i<2000000;i+=2)
{
if(isPrime(i))
{
sum+=i;
}
}
System.out.println(sum);
}
public static boolean isPrime(int n)
{
boolean prime = true;
if (n<2) return false;
if (n==2) return true;
if (n%2==0) return false;
for (int i = 3; i<=Math.sqrt(n);i+=2)
{
if (n%i==0)
{
prime=false;
break;
}
}
return prime;
}
}
Which prints out 142913828920, which project Euler tells me is wrong.
Any ideas?
(Also, I know my method for finding primes is terribly inefficient.)
for(int i =3;i<2000000;i+=2)
2 is prime.
You can accelerate your code a little bit by only dividing the prime numbers. For example, you can know that 35 is not a prime number by just trying to divide it by 2, 3, 5. No need to try 4. The trick is, any time you find a prime number, save it in a list or a vector. And in your isPrime function, just iterate the list until it hits sqrt(n) instead of every value in between 3..sqrt(n).
You can accelerate your code even more by using a Sieve.
I found the following method very efficient , when i checked if a number is prime i only divide the number by the prime numbers previously found and are below square root of n . No need to check for all the numbers below square root of n . And it only takes more than one second !!
public class Problem10 {
private static List<Long> listOfPrimes = new ArrayList<Long>();
public static void main(String args[]) {
long count = 0;
for (long i = 2; i < 2000000; i++) {
if (isPrime(i)) {
count += i;
System.out.print(i + " ");
}
if (i % 1000 == 0) {
System.out.println();
}
}
System.out.println("\nTotal " + count);
}
private static boolean isPrime(long n) {
String strFromN = new Long(n).toString();
if ((strFromN.length() != 1) && (strFromN.endsWith("2") || strFromN.endsWith("4") || strFromN.endsWith("5") || strFromN.endsWith("6") || strFromN.endsWith("8"))) {
return false;
}
for (Long num : listOfPrimes) {
if (num > Math.sqrt(n)) {
break;
}
if (n % num.longValue() == 0) {
return false;
}
}
listOfPrimes.add(new Long(n));
return true;
}
}

Categories

Resources