Codechef "Primality Test" Wrong answer - java

Problem:
Alice and Bob are meeting after a long time. As usual they love to play some math games. This times Alice takes the call and decides the game. The game is very simple, Alice says out an integer and Bob has to say whether the number is prime or not. Bob as usual knows the logic but since Alice doesn't give Bob much time to think, so Bob decides to write a computer program.
Help Bob accomplish this task by writing a computer program which will calculate whether the number is prime or not .
Input
The first line of the input contains T testcases, T lines follow
Each of T line contains an integer N which has to be tested for primality
Output
For each test case output in a separate line, "yes" if the number is prime else "no"
My solution:
`import java.io.*;
import java.math.*;
import java.util.*;
class ex6
{
public static void main(String args[])throws IOException
{
try
{
BufferedReader input=new BufferedReader(new InputStreamReader(System.in));
int t=0;
t=Integer.parseInt(input.readLine());
int n=0;
int c=0;
while(c!=(t))
{
int j=0;
n=Integer.parseInt(input.readLine());
if(n==1)
System.out.println("No");
else{
for(int x=2;x<n/2;x++)
{
if(n%x==0){j++;break;}
}
if(j==0)
System.out.println("Yes");
else
System.out.println("No");
}
c++;
} }
catch(Exception e)
{return;}}}`

Your whole approach is wrong, read about https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes. Besides, all these exercises assume that you use a known algorithm.
The idea is that you have an array with boolean values, where "true" means "prime" and "false" means "non-prime", what you do is start with an array of all true boolean values (besides 1 and 0), then starting with 2 eliminate the multiples of 2 (marking them false), then move to the next prime number, which is 3, mark false multiples of that, etc, until you're done.

Related

Hangman that saves wrong guesses in array and prints them before each guess. also prints gameboard with "_" and correct guesses

so I've been studying Java for about 3 months and I am supposed to do a Hangman code using only arrays, loops, and if statements. the word to be guesses is read from another file and saved as a string. I have to be able to save the wrong guesses in an array. and after each guess print all the wrong guesses so far, as well as the gameboard with underscores for not guessed letters and the correct guesses of course in their place. here is my code so far :
for(int l = 0; l<wordlength;l++)
{
System.out.print("_");
}
System.out.println();
System.out.println("WRONG: ");
for(int c = 0; c<numofGuesses;c++)
{
System.out.println();
System.out.print("GUESS"+guessN+"/"+numofGuesses+": ");
char guess1=in.next().charAt(0);
char guess = Character.toUpperCase(guess1);
guessN = guessN+1;
for (int j = 0; j<wordlength;j++)
{
if (guess==guessword.charAt(j))
{
System.out.println("Great guess!");
System.out.print (guessword.charAt(j));
}
else
{
System.out.print("_");
WRONG[u]=guess;
u++;
}
}
if you guess A it prints correctly "A___" but then if you guess B after instead of printing "AB__" (the word to guess is ABLE) i get "B__" also the wrong array is not storing and printing all the wrong guesses each time. please help I've been trying for 5 days and that's all I did the entire day today and I couldn't get past this.
Because this sounds a lot like a homework assignment, I will give directions for solving this, but not provide a full working solution. Hopefully, seeing how one could1 go about approaching such a problem is enough of a step in the right direction to be able to solve it yourself.
Let's first think about what we need to do.
Read a word that needs to be guessed, say String toBeGuessed.
You did this. ✔
Keep track of the characters the player has guessed so far.
Keep track of the number of turns a player has gotten.
Keep track of if the word has been guessed (player won!).
Say that the number of guesses a player can make is fixed. This can be modeled using a constant:
/**
* Number of guesses a player can take.
*/
public static final int NUM_GUESSES = 10;
Now let's think about the main logic of our hangman game. It is good to first think about the structure of your program and only later actually implement it. When thinking of the program structure, we don't bother with specifics of the programming language of your choice yet. In pseudocode, it would be something like the following, maybe (let's indicate what you already have with ✔).
for turn from 1 upto NUM_GUESSES do ✔
show player what they guessed so far
show the gameboard
ask player for their new guess ✔
save player's guess and update internal state
check if the player won, let them know if they did
if player did not win
let them know
Right. So, we need to somehow store the guesses that a player made. Every guess is a character, and we know there will be at most NUM_GUESS guesses in total. A good option (and one that is suggested by your exercise) is an array!
/**
* Characters that have been guessed so far.
*/
private char[] guessed;
This can be initialized as follows, since we know the maximum number of guesses:
this.guessed = new char[NUM_GUESSES];
This gives us an array of NUM_GUESSES characters that are initialized to 0 (see here). Since users won't guess that character, we can use it to represent guesses that have not been done yet. Alternatively, we can keep track of the current turn of the player in a separate variable. Your choice!
In the following, I will not keep track of the current turn in a separate variable, just to show more of arrays and loops. It might be a fun exercise to change this to using an int turn variable!
show player what they guessed so far
Alright, this should be fairly straightforward now. We basically need to print the part of the guessed array that is not 0. That can be done using a loop, like so for example:
System.out.print("You so far guessed: ");
for (int i = 0; i < guessed.length; ++i) {
if (i > 0) {
System.out.print(", ");
}
if (guessed[i] != 0) {
System.out.print(guessed[i]);
} else {
break; // stop the loop as soon as we run into a 0
}
}
System.out.println(".");
This will print something like You so far guessed: a, b, c. when the player guessed those characters. See how we only print the comma when some other character was printed before?
show the gameboard
The next point of the program structure is trickier to get right. Let's think a bit about structure again.
for each character in toBeGuessed
if the character has been guessed
print it
else
print an underscore
Looping over every character of a word can be done as follows.
int length = toBeGuessed.length();
for (int i = 0; i < length; ++i) {
char character = toBeGuessed.charAt(i);
// do something with character here
}
How do you find if a character has been guessed yet? Well, by checking if it is stored in the guessed array. This again can be done using a loop. That loop will be very similar to the one we have written above, when showing what the player guessed so far. I think you should be able to figure that one out.
save player's guess and update internal state
We move on to the next point of the program structure. Say that we have a char guess that the player guessed. We need to store this in our array guessed. Where? Well, at the first open spot, that seems a reasonable choice. To find that one, let's use a loop again, and break the loop when we have found an open spot.
for (int i = 0; i < guessed.length; ++i) {
if (guessed[i] == 0) {
guessed[i] = guess;
break;
}
}
check if the player won, let them know if they did
What we need to know in order to see if the player won, is simply if the number of characters they guessed right is equal to the number of characters in toBeGuessed. You could modify the loop for showing the gameboard to not print characters, but count correct ones. Then at the end compare to toBeGuessed.length() and if they are equal, the player won.
if player did not win, let them know
This should be fairly easy, if you got the previous point working.
When you did all the above and stitched it together, you should have a working version of hangman. Your very own, something to be proud of!
Some tips and tricks:
you can implement most of the points described above as separate methods;
when you do so, you can write one main method that calls the other methods (this will make it easier to read your own code and make changes to it);
try to put as little code as possible in the main method.
Here is a little template that you can start from.
import java.io.PrintStream;
import java.util.Scanner;
public class HangMan
{
/** Number of guesses a player can take. */
public static final int NUM_GUESSES = 10;
/** Word to be guessed in a game of hangman. */
private String toGuess;
/** Letters that have been guessed so far. */
private char[] guessed;
/**
* Construct a new game of hangman, ready to be played.
*/
public HangMan(String toGuess)
{
this.toGuess = toGuess;
this.guessed = new char[NUM_GUESSES];
}
// your other methods go here
/**
* Read guesses from given input and print results to given output.
* Continues until guesses have run out, or word was guessed.
*/
public void play(Scanner in, PrintStream out)
{
for (int round = 0; round < NUM_GUESSES; ++round) {
showGuessedSoFar(out);
showGameBoard(out);
char guess = askGuess(in, out);
saveGuess(guess);
if (hasPlayerWon()) {
out.println("You won!");
return;
}
}
// at this point, player ran out of guesses and hence lost
out.println("You lost...");
}
/**
* The bit that runs our hangman game.
*/
public static void main(String[] args)
{
// read word to guess from arguments, with a default value
// you would probably insert your "read word from file" code here
HangMan game = new HangMan(args.length >= 1 ? args[0] : "ABLE");
// play a game, using system input and output
game.play(new Scanner(System.in), System.out);
}
}
Good luck!
TL;DR. Trying to teach one how to think about a problem and how to write code that executes the solution one thought of. Features some example code with arrays and loops.
1 This is only one possible solution, there are always many ways to solve a given problem.

Need help Spotting A logic error in my program (prime numbers) / understanding output

New to programming.
Before you comment: I understand that their are more efficient ways to do this, and already have. I just feel that understanding the process here will make me a better programmer.
Following pseudo code I saw in class. I wrote a program that takes a integer and prints every prime number up to and including the integer(userinput).
This is what I came up with:
//Import Scanner.
import java.util.Scanner;
//Create class.
public class QuestionTwoA2
{
public static void main(String[] args)
{
System.out.println("Enter an integer:"); //Ask for user input.
int userInteger; //Create scanner object and collect user input.
Scanner keyboard = new Scanner(System.in);
userInteger = keyboard.nextInt();
boolean primeFlag = true; //Condition required for prime number loop.
int outer; //I localised these variables outside the loop so that I
int inner; //could test output by printing it.
//Checks natural numbers in between 2 and userInteger.
for (outer = 2; outer < userInteger; outer++)
{
for (inner = 2; inner < outer; inner++)
{
if (outer % inner == 0)
{
primeFlag = false;
//System.out.println(outer + " " + inner);
break;
}
}
if (primeFlag) //I think this statement causes a logic problem.
System.out.println(outer);
}
}
}
I have/had print statements in various parts of my code just to visualise what values I am comparing to get a remainder. My current output is (for any integer input):
Enter an integer:
9
2
3
Logically my code looks fine but obviously doesn't work, help explaining what is actually going on would be much appreciated.
You should put "boolean primeFlag = true;" inside the first for and before the second for.
Since second for is for detecting whether the "outer" variable is a prime number or not, so before going into that you should set your flag true which is your assumption at first, and in second loop when you are checking all smaller values to see whether it is actually prime or not and change the flag if not.

Java Excercis 16 RandomWalk

I am running a program that starts someone in the middle of a 7 foot bridge and you have to generate 1s and 0s to simulate forward and backward steps. It is supposed to calculate how many steps it took the person to fall off either forwards or backwards, and i am not done but when i run it, it never stops generating numbers. this is what i have so far:
import java.util.Scanner;
import java.lang.Math;
public class RandomWalk {
public static void main(String[] args){
int forwardstep=4;
int backwardstep=4;
int average;
int randomnum=0;
int attemptnum=0;
Scanner input=new Scanner(System.in);
while(forwardstep<7||backwardstep<7){
randomnum=(int)(2*Math.random()+0);// random number generator//
System.out.println(randomnum);
attemptnum+=1;
if(randomnum==1){
forwardstep+=1;
backwardstep-=1;
}
else if(randomnum==0){
backwardstep+=1;
forwardstep-=1;
}
}
input.close();
}
}
while (forwardstep<7 || backwardstep<7)
You are looking for a fall off one side of the bridge so one of these will always be true. You want to check rather if one of these if false therefore;
while (forwardstep<7 && backwardstep<7)
Because when you add one to one of your variables you always quit one on the other. For example, look at this:
forwardstep=4;
backwardstep=4;
5-3,6-3,7-3
But when the other variable enter in the if, then you will have this:
6-4,5-4,4-6,3-7
So, it's impossible that in the same time both variables will be equals to 7. Maybe you have to change the condition of your while to && (AND operator).

Game of dice in java

The requirements of the program are:
Antonia and David are playing a game.
Each player starts with 100 points.
The game uses standard six-sided dice and is played in rounds. During one round, each player rolls one die. The player with the lower roll loses the number of points shown on the higher die. If both players roll the same number, no points are lost by either player.
Write a program to determine the final scores.
I came up with the following code:
import java.util.*;
public class prob3
{
public static void main(String[]args)
{
Random g=new Random();
int a,b,c;
int rounds;
int antonio=100;
int david=100;
Scanner s=new Scanner(System.in);
System.out.println("Please enter the no. of rounds you want to play(1-15): ");
rounds=s.nextInt();
for(int d=1;d<=rounds;d++)
{
a=g.nextInt(6)+1;
b=g.nextInt(6)+1;
System.out.println("Round "+d+":"+a+" "+b);
if(a<b)
antonio=100-b;
else if(a>b)
david=100-a;
}
System.out.println("Total for Antonio: "+antonio);
System.out.println("Total for David: "+david);
}
}
The program fails to calculate the right sum at the end.
What am I doing wrong?
Any help would be appreciated.
Thanks.
You are doing this.
antonio=100-b;
When you probably want
antonio = antonio - b;
The first code simply subtracts the dice roll from 100 every time, which is pointless. You want to subtract the dice roll from the players totals. Do this for both players.
As stated above the "100 - b" was your main problem. But there is no reason in your problem statement to set a number of rounds.
I whould rather use a loop like this:
while(antonio >= 0 && david >= 0){
//do the same stuff here
}
System.out.println...
Since it looks as some exercise for some java course.. This may sound useless but:
Format always your code.. Spaces, brakets and tabs
Use descriptive variable mames. a b c d are not quite intuitive in a larger program.
Remover unused variables
Y mucha suerte tío!

SPOJ ADDREV Problem

I did go through the other threads on this SPOJ problem, ADDREV (Adding Reversed Numbers), but sadly, I was not able to get an answer by any of the three programs that I have written (in C, Python and Java). I am attaching the code snippets of all three.
Python:
def find_rev(a):
d=0
while(a>=1):
d=d*10+a%10
a=a/10
return d
n=input('enter a number')
for i in range(int(n)):
num1=input('enter the first number')
num2=input('enter the second number')
num=0
num1=find_rev(int(num1))
num2=find_rev(int(num2))
num=num1+num2
num=find_rev(num)
print num
With Python, I get a runtime error.
With C, I get a wrong answer.
#include<stdio.h>
long rev(long);
int main()
{
long int n;
long int n1;
long int n2;
long int i=0;
scanf("%ld",&n);
//printf("%d",n);
for (i=0;i<n;i++)
{
//printf("\n%d",i);
//printf("\nenter the two numbers");
scanf("%ld%ld",&n1,&n2);
n = rev(rev(n1)+rev(n2));
printf("%ld\n",n);
}
return 0;
}
long rev(long a)
{
long d=0;
while(a>=1)
{
d = d*10+a%10;
a = a/10;
}
return d;
}
With Java, I get a compilation error.
import java.util.*;
//import java.io.*;
public class spoj_prob {
public static void main(String args[])
{
long n=0;
System.out.println("enter a number \n");
Scanner in=new Scanner(System.in);
n=in.nextLong();
long n1=0;
long n2=0;
long sum=0;
for (int i=0; i<n; i++)
{
System.out.println("enter two numbers \n ");
n1=in.nextLong();
n2=in.nextLong();
n1=rev(n1);
n2=rev(n2);
System.out.println(n1);
System.out.println(n2);
sum=rev(n1+n2);
System.out.println(sum);
}
}
static long rev(long a)
{
long d=0;
while (a>=1)
{
d=d*10+a%10;
a=a/10;
}
return d;
}
}
}
Of course, those errors are reported by the SPOJ Judge. The programs work fine on my system. Test cases I use are:
2
999999999 11
999 11
Answer
101
101
Also
3
34 54
123 091
00034 00054
Update: Guys, I got the answer in C. Thank you for all the help.
Before you start using any service, it's generally a good thing to read its FAQ. It explains how exactly the program should receive data.
In particular, please notice that printing enter a number and other junk to the console will always lead to a wrong answer. Because a correct program would output something like
34
1998
1
and yours
enter a number
enter two numbers
34
enter two numbers
1998
enter two numbers
1
I can't tell why Java fails to compile, though. You probably should find some information on how to submit in Java with the reference solution.
Also, the problem definition gives no limit for input numbers, so they can possibly be too big for standard integer types in Java and C++.
With Python I think you're getting Runtime Error because you're calling a restricted function input, nothing else comes to mind.
In C you're getting WA because the input integers can be very large, and you're overflowing.
For JAVA there are 2 potential problems that you may have. One is that you're using Scanner class which may not be supported by SPOJ (due to security or other considerations). Second, is that your class name needs to be Main I think. Please search SPOJ forum for more details on this.
Try this solution in Python 3:
import sys
t = int(input())
i=0
while i<t:
a,b = map(int,sys.stdin.readline().split()) #to take both inputs in single line
c=str(a) #converting the number into string
d=str(b)
e=int(c[::-1]) #converting reverse of the string c to int
f=int(d[::-1]) #converting reverse of the string d to int
s=e+f #adding the two reverse numbers
s1=str(s)
s2=int(s1[::-1]) #reverse s and display it
print(s2)
i+=1

Categories

Resources