Range of divisors (Java) - java

I'm not quite sure what I'm having trouble with here and I'm hoping someone can help me. This is my first post on Stack Overflow, and I'm relatively new to programming, so I hope I don't offend anyone's sensibilities around here.
Here's the prompt (yes, it's a Project Euler question and please don't give the answer away): What is the lowest number which is divisible by every number between 1 and 20?
Here's what I coded:
int target = 21;
int divisor;
boolean success = false;
while (!success)
{
for (divisor = 1; divisor < 21; divisor++)
{
if (target % divisor != 0)
{
break;
}
else
{
if (divisor == 20)
{
success = true;
}
}
target++;
}
}
System.out.println(target);
The answer I'm getting (232792581) is being flagged as incorrect by P.E. Can anyone tell me what I'm getting wrong here?
Thanks everyone!!

Your problem is that you have target++ in the wrong place. The way your code is now, this is being called inside the for loop where you test the numbers - i.e. you change the target while checking things against it. Move the target++ statement so that it is out of the for loop but still in the while loop.

Related

Random number guessing game with limitations after each guess

I am making a number guessing game:
The computer generates a number inside an interval
I try to guess it and receive a reply whether it's higher/lower than my guess or equals to my guess and I've won
There is an interval in which I can guess, as well as a guess attempt limit
The trick is, however, that I need to implement another condition: each guess should "shrink" the interval in which I'm able to guess. For example: computer generates 50, I guess 25, computer replies "The random number is larger.". Now knowing that, I should not guess anything lower than 25 again, it's unreasonable. In case I guess i.e. 15, the computer should reply "The guess doesn't make sense.". I understand that I somehow need to save each guess value to a new variable, but nothing seems to work. I'm a beginner, please bear with the following code, I've tried a lot of things:
public String guess(int guess)
{
int lowerBound = 0;
int upperBound = 99;
Set<Integer> lowerGuesses = new TreeSet<>();
Set<Integer> higherGuesses = new TreeSet<>();
if (gameOver) {
return "The game is over.";
}
if (guess < 0 || guess > 99) {
return "The guess is out of bounds.";
}
if (guessCount < maxGuessCount) {
if (guess < secretNumber) {
if (lowerGuesses.contains(guess)) {
return "The guess doesn't make sense.";
}
else {
guessCount++;
lowerBound = guess;
lowerGuesses.add(guess);
return "The random number is larger.";
}
}
if (guess > secretNumber) {
if (higherGuesses.contains(guess)) {
return "The guess doesn't make sense.";
}
else {
guessCount++;
upperBound = guess;
higherGuesses.add(guess);
return "The random number is smaller.";
}
}
if (lowerGuesses.contains(guess)) {
return "The guess doesn't make sense.";
}
if (higherGuesses.contains(guess)) {
return "The guess doesn't make sense.";
}
}
if (guess < lowerBound || guess > upperBound) {
return "The guess doesn't make sense.";
}
if (guessCount == maxGuessCount) {
gameOver = true;
victorious = false;
return "Ran out of guess attempts.";
}
guessCount++;
gameOver = true;
victorious = true;
return "You won.";
}
Thank you in advance!
First, to avoid confusion, let's rename the method in order to make sure that its name is not an exact match with its parameter, so this is how it should look like:
public String makeGuess(int guess)
avoid naming different entities in the same name space with the exact same name (local variables being present in different methods or parameters having similar names with data members for the purpose of initialization are an exception). From now on, you will call the method as makeGuess(25), for example.
Now, to the actual problem. You have an incorrect assumption. You assume that you need to keep track of past intervals. That's not the case. You can just change the edges of the intervals. Also, your code is superfluous, I advise you to refactor it. Finally, you always initialize upper bounds, local bounds and higher and lower guesses as local variables, so they will never be kept track of. Instead of this, you need to perform the following simple measures in order to make this work:
Define the bounds and limit as data members
protected int lowerBound = 0;
protected int higherBound = 99;
protected int lb = 0;
protected int hb = 99;
protected int limit = 5;
protected int guessCount = 0;
protected int randomizedNumber; //Initialize this somewhere
Note that I have hard-coded some values. You might want to make this dynamic with initialization and stuff like that, but that's outside the scope of the answer. lowerBound, higherBound, limit are game settings. while lb, hb, guessCount represent the game state. You could separate this logic into another class, but for the sake of simplicity, even though I would program differently, I will leave them here in this case.
Have a method that initializes the game
public void initialize() {
lb = lowerBound;
hb = higherBound;
guessCount = 0;
}
So you separate your concern of game initialization from the outer logic of starting and maintaining a game.
Implement makeGuess in a simplistic way
public String makeGuess(int guess) {
if (++guessCount >= limit) return "The game is over.";
else if ((lb > guess) || (hb < guess)) return "The guess doesn't make sense";
else if (randomizedNumber == guess) return "You won.";
else if (guess < randomizedNumber) {
hb = guess;
return "The random number is smaller.";
} else {
lb = guess;
return "The random number is larger.";
}
}
NOTE: I dislike mixing up the logic with the output layer, the reason I did it in the method above was that you have mentioned you are a beginner and my intention is to make this answer understandable for the person who just begun programming and is very confused. For the purpose of actual solutions, you should return a state and in a different layer process that state and perform the console/UI operations you need. I will not go through the details now, as it would also be outside of scope, but for now, please have some success with the solution above, but THEN you should DEFINITELY look into how you need to code, because that is almost as important as making your code work.

Why do I get no output out of println in this case?

I tried this a lot, and debugged it a few times, everything seems to be working and largest prime does indeed become the largest prime even if it takes rather long.
I can't get the printed value from System.out.println. I could find it through the debugger but the value is too high to find fast just holding down step over.
It compiles as well so I am stumped about what's the issue here. I would be very happy to know what I did wrong.
Edit: The reason why I wrote this code in the first place is because in the site project euler it asked for the largest prime value that when divided with the value of primer gave a whole number.
Is there a way at least that would allow me to make it faster with the same value? this seems rather impractical.
package unit5;
public class Primefinder { public static void main(String[] args)
{
double primer = 600851475143d;
double largestprime = 0;
Boolean ifprime = false;
for(double x = 2d; x < primer; x++)
{
for(double z = 2d; z<x; z++)
{
if( (x%z == 0) && (z != x) )
{
ifprime = false;
break;
}
else {
ifprime = true;
}
}
if((ifprime != false) && (x > largestprime))
{
largestprime = x;
}
ifprime = false;
}
System.out.print(largestprime);
}
}
for other questions you might ask everywhere, please tell us that what is the purpose of your code. this way it is easier to get the fault.
the code you have written above runs completely but the numbers you have used are too big so you need to wait a lot, so that compiler be able to reach to this line:
System.out.print(largestprime);
use lower numbers (at least for test) or wait properly.
Your 'primer' Value is very big.
So, loop is taking very much time to reach at '600851475143' value.
Wait Sometime and it with show largest prime number

JAVA Max Value from a String that contains only digits

I have some problem with an exercise from geeksforgeeks portal. I don't know why they say to me wrong answer. I have completed the function and my results on their visible test cases is good. Maybe i don't understand what they want from me to solve in the problem? Can you help me please?
The problem is this
My code is this:
//Your Code here
long answer = 0;
for (int i = 0; i < str.length(); i++)
{
long multiply = (str.charAt(i) - 48) * answer;
long sum = (str.charAt(i) - 48) + answer;
if (multiply > sum)
answer = multiply;
else if (sum > multiply)
answer = sum;
}
System.out.println(answer);
And as you can see... my solution works for the visible test cases:
Important!!! They don't show the input test cases where the code have failed. They don't show any input of the test cases.
EDITED:
some request of custom input to show (also changed a little the if else statement... included now the possibility of equals sum and multiply
Your code contains a small bug due to the following if-else statements:
if (multiply > sum)
answer = multiply;
else if (sum > multiply)
answer = sum;
You forgot the condition when sum equals multiply. In that case, your answer variable remains unchanged in that iteration and you will get a wrong answer finally.
Now sum == multiply can occur for the test case of "22" --> your code gives answer as 2, while the answer should be 4.
This might be one of the test cases failing for your code.

Why is my while going in a infinity loop? How do I fix it?

I dont know why my do while is going on infinity and not showing my output which should be how many quaters, dimes ,etc has that amount of money that the user input in the system.
Scanner scan = new Scanner(System.in);
System.out.println("Enter the amount of money: ");
float dinero= scan.nextFloat();
int quaters=0;
int dimes =0;
int nickle =0;
int pennys =0;
boolean b=false;
do{
if(dinero>=0.25){
dinero=(float) (dinero-0.25);
quaters++;
}else if(dinero<0.25 && dinero>=0.10){
dinero=(float) (dinero-0.10);
dimes++;
}else if(dinero<0.10 && dinero>=0.05){
dinero=(float) (dinero-0.05);
nickle++;
}else if(dinero<0.05 && dinero<0){
dinero=(float) (dinero-0.01);
pennys++;
}else{
b=true;
}
}while(b==false);
System.out.println("Quater :"+quaters);
System.out.println("Dimes :"+dimes);
System.out.println("Nickle :"+nickle);
System.out.println("Pennys :"+pennys);
Please help i know this is a dumb question but help will be much apprishiated.
Not sure what you are trying to do but here is your problem: the last else is never executed because you covered all the possible cases in the if instructions before. Because of that, b will always be false and therefore your loop will go on forever. In which condition do you exactly want to exit this loop? Think about this and then move the instruction in the last else into the corresponding if block. Also, the if before that is not correct either. You probably meant:
if(dinero<0.5 && dinero>=0){
//do stuff
}
I fix it it was that my last condition was wrong. Also the while was wrong
else if(dinero<0.05 && dinero>=0.01){
// was the the fix for the last else if
while(dinero>0.01);
// and here is the while
change the condition of your else if statement to
else if(dinero<0.05 && dinero>0)

Better approach for multiple if else statements?

I have a program that takes in 3 numbers (feet, inches, sixteenths) then multiplies them by x. Upon starting to write the output part, I ran into needing:
if (sixteenths4<16) {
sixteenths5=sixteenths4;
inches6=0;
}else if (16<=sixteenths4) {
sixteenths5=sixteenths4-16;
inches6=1;
}else if (32<=sixteenths4) {
sixteenths5=sixteenths4-32;
inches6=2;
}else if (48<=sixteenths4) {
sixteenths5=sixteenths4-48;
inches6=3;
} else {
sixteenths5=sixteenths4-64;
inches6=4;
}
I realize the last else is redundant as it will never happen. My issue is that since the total sixteenths could exceed 4-5 hundred, that would be a lot of if else blocks. Is there a better way to do this?
Remive all the if/else statements and use integer arithmetic instead.
This is equivalent code for all your code:
sixteenths5 = sixteenths4 % 16;
inches6 = sixteenths4 / 16;

Categories

Resources