How to check for divisors within an array [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have one array of n cells with cell 0 having int 0 and cell 1 with in 2 ect... [0,2,3,4,n...]
My goal is to have the the user select a value(not cell #) in the array, the selected value then becomes a zero ONLY IF both of the following condition below are true:
The user cannot chose a cell that is already a 0
The user cannot chose a number that does not a remaining divisor in the array. For example; the user cannot chose 3, 4 or 7 in an array containing [0,0,3,4,0,6,7,8]
Any number that the user selected to be unavailable will have System.out.println ("Invalid number");
EDIT: My current problem right now is when I have [0,0,0,4,5,6] I can select 4,5 and 6 and turn it into a zero even though there is no divisor for any of these number.
My try for the code, not fully working:
int[] NumBox = new int[StartNum];
for (int i = 1; i < NumBox.length+1; i++)
{NumBox[i - 1] = i;}
if (NumBox[pick-1]!= 0)
{
boolean hasDivisor = false;
for (int k = 1; k < NumBox.length+1; k++)
{
if (NumBox[k] == 0)
continue;
if (NumBox[pick-1] % NumBox[k] == 0)
{
hasDivisor = true;
break;
}
}
if (hasDivisor)
{
score1 = pick + score1;
NumBox[pick-1]=0;
}
else
System.out.println ("Invalid number");
}
Thanks for any help.

You don't say what the problem is with your current code, but I'm guessing that you probably want to change this test:
if (NumBox[pick-1] % NumBox[k] == 0)
to this:
if (NumBox[pick-1] > NumBox[k] && NumBox[pick-1] % NumBox[k] == 0)
That way you won't consider a number as its own divisor.

Ok.. here's an approach.
1. Sort the array in ascending order.
2. For a given number/input say "n" at index say "i",
if any number before index "i" has number!=0 && n%number ==0, then it is divisible. Else, it is not divisible

Simple approach is this
1. Sort the array in ascending order.
2. Now when the user selects a number, keep testing
the mod value from start until root(N) of that number.
If none mods to zero, then it doesn't have any divisors.
The first part should be easy, the second part would be something like this pseudocode
boolean flag=false;
if(!(pick==0)){ // testing if it is already is not zero
for (int i = 0; i < args.length; i++) {
if(pick%NumBox[i]==0){
//divisor found
flag=true;
break;
}else if(NumBox[i]>Math.sqrt(pick)){
//No divisors found
break;
}
}
}
if(flag==true){
pick=0;
}

Related

Java Question .What is the problem in my code?

Sometimes, the normal if-else isn't enough. In such cases, we have what we call ladder if and else conditions. So here we'll learn to use them.
Given a positive integer N. Your task is to check if it divisible as given below:
If it is divisible by 2, print "Two".
If it is divisible by 3, print "Three".
If it is divisible by 11, print "Eleven".
If not follow above three rules, print "-1".
Note: If N is divisible by more than one of the above given numbers, print the one which is largest.
Input Format:
First line of input contains number of testcases T. For each testcases, there will be a single line containing N.
Output Format:
For each testcase, check divisibility and print statements accordingly as given in above steps (without quotes).
Your Task:
Your task is to complete the function to check divisibility as required.
Constraints:
1 <= T <= 10
1 <= N <= 106
Example:
Input:
2
3
11
Output:
Three
Eleven
** For More Input/Output Examples Use 'Expected Output' option **
class Geeks {
static void isDivisibleByPrime (int n)
{
//Your code here
Scanner sc=new Scanner(System.in);
int a[]=new int[n];
for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();
if(a[i]%2==0)
System.out.println("Two");
else if(a[i]%3==0)
System.out.println("Three");
else if(a[i]%11==0)
System.out.println("Eleven");
else
System.out.println("-1");
}
}
}
First use braces around every block of code. it is easier to reading for everyone.
Second the point in your spec was to print the largest value if divisible, so you
should start with checking if it divides by 11 first, then 3 and then 2.
Right code is here:
static void isDivisibleByPrime(int n) {
if (n % 11 == 0) {
System.out.println("Eleven");
} else if (n % 3 == 0) {
System.out.println("Three");
} else if (n % 2 == 0) {
System.out.println("Two");
} else {
System.out.println("-1");
}
System.out.println();
}
First things first - always use braces around every block of code - especially a beginner to the language. It will make your life easier, and anyone reading your code.
Second, the point in your spec was to print the largest value if divisible, so you should start with checking if it divides by 11 first, then 3 and then 2.
And lastly, I would get all the input first, and not in the isDivisibleByPrime method, and just call that method for each input.
So just leave your isDivisibleByPrime as
static void isDivisibleByPrime(int n) {
if (n % 11 == 0) {
System.out.println("Eleven");
} else if (n % 3 == 0) {
System.out.println("Three");
} else if (n % 2 == 0) {
System.out.println("Two");
} else {
System.out.println("-1");
}
}
And call it elsewhere with the values
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of test cases:");
int numOfTestCases = sc.nextInt();
for (int i = 0; i < numOfTestCases; i++) {
System.out.println("Enter value to check:");
int valueToCheck = sc.nextInt();
isDivisibleByPrime(valueToCheck);
}
Obviously there's no error handling or whatnot, but as you're likely new to this, I'm sure it's not a requirement.
Here's an online example.

Can someone explain the algorithm of this java program? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I found it in the net and I want to know the explanation of it's algorithm.
I'm having a hard time to understand this. thank you so much :)
import java.util.Scanner;
class BinarySearch
{
public static void main(String args[])
{
int c, first, last, middle, n, search, array[];
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];
System.out.println("Enter " + n + " integers");
for (c = 0; c < n; c++)
array[c] = in.nextInt();
System.out.println("Enter value to find");
search = in.nextInt();
first = 0;
last = n - 1;
middle = (first + last)/2;
while( first <= last )
{
if ( array[middle] < search )
first = middle + 1;
else if ( array[middle] == search )
{
System.out.println(search + " found at location " + (middle + 1) + ".");
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if ( first > last )
System.out.println(search + " is not present in the list.\n");
}
}
I'll appreciate your response. thanks again.
The binary search algorithm begins by comparing the target value to the value of the middle element of the sorted array. If the target value is equal to the middle element's value, then the position is returned and the search is finished. If the target value is less than the middle element's value, then the search continues on the lower half of the array; or if the target value is greater than the middle element's value, then the search continues on the upper half of the array. This process continues, eliminating half of the elements, and comparing the target value to the value of the middle element of the remaining elements - until the target value is either found (and its associated element position is returned), or until the entire array has been searched (and "not found" is returned).
Here is your answer beautifully explained :
check this out
http://www.csit.parkland.edu/~mbrandyberry/CS1Java/Lessons/Lesson27/BinarySearch.htm

A simple java program to find the largest prime factor of a large number(here 600851475143) compiled with no errors but not giving any output [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 8 years ago.
Improve this question
I'm not finding any fault with my program. Please point out my mistake and help me.
Code is written below:
class largest
{
public static void main(String...args)
{
double n,i,f=1.0;
n=600851475143L;
largest ob= new largest();
for(i=n/4;i<n/2;i++)
{
if(n%i==0)
{
if(ob.isprime(i) == 1)
f=i;
}
}
System.out.println(f);
}
int isprime(double k)
{
int s,i=2,flag=0;
while(i<k && flag==0)
{
if(k%i==0)
flag=1;
}
if(flag==0)
return 1;
else
return 0;
}
}
Your function isprime is in most cases an endless loop. It never increments i in the loop.
Every time you write a loop, you should think about the so called loop variant. This is numerical property of the loop, that is both:
A positive integer in each loop run
Decreasing during successive iterations of the loop
If you cannot think about such a property, you are in big trouble, because you have very likely an endless loop.
In your example, that property should be the number whose prime factor you want minus the current prime factor candidate you are checking.
In your current code, if you calculate the loop variant, you will get a positive integer (good), but it will not decrease (bad). As an consequence, you will wait forever, because you have an endless loop.
While other answers show nice solutions to make your code more efficient, this won't help you very much: an efficient endless loop still won't give you any result.
Your code is far too slow, that's why it takes so much time to execute and doesn't return any output (apparently). You should speed up your isPrime test using the following trick : if n is not a prime, it can be written as n = p x q where p <= sqrt(n) and q > p. Then, you can stop your loop at sqrt(n) since you are able to tell that n is not a prime if there is no integer p <= sqrt(n) verifying this property.
The following code uses that remark but also another property : a integer can always be written as 6*p + q where p and q are integers and q < 6. For all p, 6*p + 2 and 6*p + 4 are divisible by 2 and 6*p + 3 is divisible by 3 so for all n = 6*p + q, if n is not divisible by 2 nor by 3, then n has the form 6*p + 1 of 6*p + 5 (or 6*p - 1, which is equivalent).
public static boolean isPrime(int n) {
if (n == 2 || n == 3)
return true;
if(n <= 1 || n % 2 == 0 || n % 3 == 0)
return false;
int x = (int) Math.sqrt(n);
for(int i=1 ; (6*i-1) <= x ; i++)
if(n % (6*i-1) == 0 || n % (6*i+1) == 0)
return false;
return true;
}
Edit :
Plus, as stefan.schwetschke observed, you are not incrementing the index of your loop. In this case you should use a for loop since you now exactly the bounds of the index of the loop.
This is not a "code" answer (none of the other answers will provide a solution in a reasonable amount of time , even when correcting your brute force original code).
You may want to explore prime factorization algorithms, with Pollard-Strassen algorithm (or Rho Pollard algorithm).
Some research links include:
Wolfram Research http://mathworld.wolfram.com/PollardRhoFactorizationMethod.html
Colorado State University lecture http://www.cs.colorado.edu/~srirams/classes/doku.php/pollard_rho_tutorial
and here https://math.stackexchange.com/questions/185524/pollard-strassen-algorithm
(for mathematics on stackexchange.

what this method does - interview [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
The following is an interview question... how can you start solve this kind of a question ? is there a general algorithm for such a questions ?
The question is to explain what this method does. I know what she gives for some inputs I tried (and it's OK), but I really don't know how to start solve this kind of a questions...
public boolean what (int num)
{
boolean ans = true;
for (int x = 2; (x*x <= num) && ans; x=x+1)
{
if ((num % x) == 0)
ans = false;
}
return ans;
}
thx !
let num = 10
public boolean what (int num)
{
boolean ans = true;
for (int x = 2; (x*x <= num) && ans; x=x+1)
{ //^ multiply x with x will give (4,9).. When x = 4, than (16<= num) = false
if ((num % x) == 0) // divide 10 by (2,3) if reminder is zero that means 10 is not prime
ans = false; // set ans to false so that for loop can be terminated or just break;
}
return ans;
}
Reverse engeering process you can follow, provide the some sample input and get the output by which you can determine the result.
Choose your input sensibly so that it would easy to solve the problem.
In present case -
Input : 1 return : true
Input : 2 return : true
Input : 3 return : true
Input : 4 return : false
Input : 5 return : true
...
Input : 9 return : false //aha...it seems to be prime number
...
Input : 111 return : false
So in this case its prime number logic.
You can find it running the method with several random inputs,
and try to find the relation between INPUT you gave and OUTPUT that appeared.
Before getting to conclusion just check it Known Output first and then declare your answer.
It checks if the num is a prime.
To find out what a method does read the code and try to understand what it is doing. You may also try some inputs. For good code the names of variables and methods also help a lot (which is not the case here).
However, if the method implements an algorithm you do not know and you do not know the context of the problem that is being solved you probably never find out what it does.
In the above program initially the number is assumed to be not prime. If any number greater than 2 and less than or equal to the square root of the number divide the given number then the number is not prime.
The method returns true if the number is not prime and returns false if the number is prime.
Purpose of method : to find out prime numbers.
This method gives an output of booleaan ans = 'true' , if input number is prime number.
Else it gives a return value of false.
It follows the simplest logic to find out if a number is prime or not..
for example if a number is 11 ,
Step 1 - we multiply it with a num till (num*num) is smaller than 11. {no need to test beyond value bigger then num*num, as all possible cases are tested }.
Step 2 - check if remainder of dividing 11/2 is zero or not , if remainder is not 0 then 11 is not prime.if it divides we go back to step 1
So the loop will be ..
Step 1 num = 11 , x = 2
Step 2 11%2 != 0 so goto step 1 , num undivisible
Step 1 num =11 , x = 3
Step2 11%3 != 0
Step 1 num = 11 , x = 4 but x*x = 16 and 16> 11 so no more looping and 11 is prime as it wasn't divisible with any number till x=3.
another example can be 38..
step 1 num 38 , x=2
step 2 38%2 ==0 , so remainder = zero and ans = false thus no more looping through and '38' is not prime.
a more advanced approach to finding a number if its prime or not could be to test its divisibility only against prime numbers. which is actually more efficient in case we have quite bigger numbers as input.
public boolean what (int num) // number to be tested is passed
{
boolean ans = true; // default value
for (int x = 2; (x*x <= num) && ans; x=x+1) //looping till num is found divisibl
{
if ((num % x) == 0)
ans = false; // ans is false in case num is not prime
}
return ans; // num is prime
}
Hope the explanation helps.. message me in case of any doubt or help.

Java Netbeans 6.5 Mastermind Calculating White Pegs

For my Mastermind Game I am using 6 numbers instead of 6 colours. Also instead of showing black and white pegs, just 2 sentences are outputted. One reads:
"The number of correct digits in the right position is __ "(black pegs/bothRight)
"The number of correct digits in the wrong position is __ "(white pegs/numberRight)
For the 4 digit guesses that are submitted, I am using an array called guessArr, which accepts 4 values from 4 input boxes.
guess0 = Integer.parseInt(firstInput.getText());
guess1 = Integer.parseInt(secondInput.getText());
guess2 = Integer.parseInt(thirdInput.getText());
guess3 = Integer.parseInt(fourthInput.getText());
//New array to arrange guesses
int[] guessArr = new int[] {guess0,guess1,guess2,guess3};
For the answer generated by the computer,
//Create a 4 digit code made of random numbers between 1 and 6
answerArr[0]=(int)(Math.random()*6+1);
answerArr[1]=(int)(Math.random()*6+1);
answerArr[2]=(int)(Math.random()*6+1);
answerArr[3]=(int)(Math.random()*6+1);
Finding the amount of black pegs is easy:
//Calculate number of correct digits in correct position
for (int i = 0; i < 4; ++i)
{
if (answerArr[i] == guessArr[i])
{
used[i] = true;
bothRight++;
}
}
EDIT
I've Solved It!
// Calculate number of correct numbers in wrong position
//Declare variables for what digits are in the answer
Integer digit1 = 0, digit2 = 0, digit3 = 0, digit4 = 0, digit5 = 0 , digit6 = 0;
//Find what the answer digits are
for (int k = 0; k < answerArr.length; ++k){
if (answerArr [k] == 1)
{
digit1++;
}
if (answerArr [k] == 2)
{
digit2++;
}
if (answerArr [k] == 3)
{
digit3++;
}
if (answerArr [k] == 4)
{
digit4++;
}
if (answerArr [k] == 5)
{
digit5++;
}
if (answerArr [k] == 6)
{
digit6++;
}
}
//Declare variables for what digits are in the answer
Integer gDigit1 = 0, gDigit2 = 0, gDigit3 = 0, gDigit4 = 0, gDigit5 = 0 , gDigit6 = 0;
//Find the guess numbers submitted
for (int p = 0; p < guessArr.length; ++p){
if (guessArr [p] == 1)
{
gDigit1++;
}
else if (guessArr [p] == 2)
{
gDigit2++;
}
else if (guessArr [p] == 3)
{
gDigit3++;
}
else if (guessArr [p] == 4)
{
gDigit4++;
}
else if (guessArr [p] == 5)
{
gDigit5++;
}
else if (guessArr [p] == 6)
{
gDigit6++;
if (gDigit6 == 0)
{
gDigit6++;
}
}
//Find the value of correct numbers submitted in the guess
Integer correctNumbers = Math.min (digit1, gDigit1) + Math.min (digit2, gDigit2) + Math.min (digit3, gDigit3) +
Math.min (digit4, gDigit4) + Math.min (digit5, gDigit5) + Math.min (digit6, gDigit6);
//Calculate value of numberRight
numberRight = (correctNumbers - bothRight);
}
Any help would be greatly appreciated. :D Thanks.
First, I'll say up front, I'm not going to give you any code since this is either a learning exercise, so you can learn the language, or else this is a class problem.
So, lets think about this logically... One way you can you can solve this is by counting the number of a type of colors.
As an example, suppose the player guessed 2 blues, and 2 greens, and the answer has 1 blue, 1 red, and two greens.
The player guessed 3 of the right colors, so you would give them 3 white pegs UNLESS they got some in the right spot. Now, suppose that they got one of those blues in the right spot, that means they have 1 black peg, which replaces a white peg. So, the grand total is 2 white pegs, and 1 black peg.
So, to find the number of "Correct Colors" you should check each color (good chance for a loop?) and compare the number of each color that the player guessed, to the number of each color that the solution has.
Put another way, you don't want to compare the guess to the answer. You want to compare the count for each color on the guess, to the count of each color on the solution.
Then, you get "White pegs" by this pesudo-code:
int whitePegs=correctColors-blackPegs;
Edit 1: Comparing answers one color at a time
If you're going to hold the count for each color, then you're going to want to use two arrays, one for the guess, and one for the solution. Each element in the array will hold the count for the color, like this:
r=red, o=orange, y=yellow, etc.
R O Y G B
Guess: [0][2][1][1][0] (Total is 4, for 4 pegs
Actual: [1][1][2][0][0] (Total is 4) for 4 pegs
Matches:[0][1][1][0][0] (Total is 2) This is "correctColors" from above

Categories