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.
Related
I understood the logic behind the problem's solution, but in the coded solution I am a bit confused about the return statement in the end. Please explain to me what is its significance, why is it being used, etc ? (not why return is used but why is that value being returned).
class Solution {
public boolean isPalindrome(int x) {
// 2 cases x < 0 = false case
// x > 0 = test case
if (x < 0 || x % 10 == 0 && x != 0){
return false;
}
else {
int newNum = 0;
while (x > newNum){
int r = (x % 10);
newNum = newNum * 10 + r;
x /= 10;
}
//the part I am confused about - below
return x == newNum || x == newNum / 10;
}
}
}
So to understand the Logic for the return statement let us take 2 numbers
1234321
678876
So one thing here While loop is doing is to create a new number(newNum) out of X and making sure that newNum stores the reverse of X till the middle point.
So in case of 1234321 , this while loop will execute till X=123 and newNum=1234.
After exiting out from while loop with these values, out of the 2 statements in return, x == newNum / 10 will give true result hence return statement will return true.which means the number is palindrome.
Please note here that the no. digits in given integer is odd(7)
Let us now Take other example 678876
In this case when the while loop ends, the value for the X would be 678 and newNum would be 678
out of the 2 statements in return, x == newNum this time will give true result hence return statement will return true again .which means the number is palindrome.
Please note here that the no. digits in given integer is even(6)
All in all, this statement return x == newNum || x == newNum / 10;
is to make sure that we are covering the condition for both Odd and even no. of digits in the given integer X.
I have a question regarding an answer that was given here a while ago.
I came up with the same answer myself in the code attached but I'm trying to understand why do I need to divide the input number by 2 (line 10), and not just let the loop run its course till the value of the input number achieved.
1 import java.util.Scanner;
2 public class numIsPrime {
3 public static void main(String[] args) {
4 Scanner sc = new Scanner(System.in);
5 int i = 2;
6 boolean isPrime = true;
7 System.out.println("Enter a number");
8 int num = sc.nextInt();
9
10 while (i < num ) // (i <= num / 2)
11 {
12 if (num % i == 0)
13 isPrime = false;
14 i++;
15 }
16
17 if (isPrime)
18 System.out.println(num + " is a prime number");
19 else // !isPrime
20 System.out.println(num + " isn't a prime number");
21
22 }
23 }
This is the simplest way to calculate if an integer n is probably a prime:
public static boolean isPrime (int n) {
if (n < 2) return false;
BigInteger bigInt = BigInteger.valueOf(n);
return bigInt.isProbablePrime(100);
}
You can insert this function call in a loop where you can pass a new number every iteration. I am using the implementation of BigInteger provided by Java to do the calculation, rather than writing my own. UNLESS this is a homework and you are required to write your own algorithm, I would use this solution.
This base method can then be used for calculating other types of prime numbers. A complete answer can be found here.
UPDATE:
The int parameter in BigInteger.isProbablePrime(int) is a measure of the uncertainty that the caller is willing to tolerate. The larger the number, the "slower" it executes (but the more certain it is). Also, going back to the original question (already answered in the OP's comments section):
why do I need to divide the input number by 2 (line 10), and not just
let the loop run its course till the value of the input number
achieved.
This is an optimization that will make your evaluation run twice as fast. For example, suppose an evaluation of n integers take 10 minutes to complete, excluding even numbers should take half the time. That's a significant improvement. Although you should not optimize prematurely, these sort of optimizations should be done right from the get go. Basically, we all know that even numbers are not prime, so why evaluate it? You want to evaluate unknowns. In my solution, I only evaluate values greater than 2 because by definition, values less or equal to 2 are not prime. I am merely solving that by definition or by mathematical properties.
As mentioned in the comments, dividing by 2 is a simplest optimization to reduce the number of checks, however, existing code has a few issues (e.g. returning true for 0 and 1 which are NOT prime numbers) and may be further optimized:
break/end the loop as soon as isPrime is set to false
skip even numbers by incrementing by 2
calculate until i * i <= num
If this limit is reached, it means that no factor i of num has been found in the range [2, num/i], therefore by definition of the prime numbers, all the remaining numbers in the range [num/i, num] are neither the factors of num, and therefore num is prime.
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
int num = sc.nextInt();
boolean isPrime = num > 1 && (num % 2 != 0 || num == 2);
int i = 3;
while (isPrime && i * i <= num) {
if (num % i == 0)
isPrime = false;
i += 2; // skip even numbers
}
if (isPrime)
System.out.println(num + " is a prime number");
else
System.out.println(num + " isn't a prime number");
More optimizations are possible if the divisibles of 3 (except 3) are excluded similar to the exclusion of even numbers, then the search continues from 5 and the candidates for primality comply with 6n ± 1 rule (e.g., 5 = 6 - 1, 7 = 6 + 1, 11 = 12 - 1, 13 = 12 + 1, etc.):
boolean isPrime = num > 1 && (num % 2 != 0 || num == 2) && (num % 3 != 0 || num == 3);
int i = 5;
int d = 2;
while (isPrime && i * i <= num) {
if (num % i == 0)
isPrime = false;
i += d; // check only non-even numbers
d = 6 - d; // switch 2 to 4 and back to 2
}
Could anyone explain how does this method works.
public static int calculate(int n){
if (n/10 == 0)
return n;
else
return (n % 10 + calculate(n/10));
}
I input n = 15 and it get a 6 but I don't understand how the method works. please help. thank you.
The method calculates the sum of the digits.
If the n is smaller than 10, you simply return n (since the sum of digits of a single digit number is the number itself).
Otherwise you add the least significant digit (that's n % 10) to the sum of digits of the number n / 10 (which is calculated recursively).
For n = 15 , here is how it works
15/10 > 0 , so the else condition is executed.
15%10 + calculate(15/10) i.e 5 + calculate(1).
The method is called again for n = 1;
Since 1/10 == 0 , 1 is returned
This 1 is then added to 5.
Therefore answer is 6.
So what this function does is return the sum of the digits that make up the number.
It goes like this:
calculate(15);
evaluates to
15%10 + calculate(1);
evaluates to
5 + 1;
which in the end; sums up to 6.
In other words; the above is an recursive approach to sum all the digits in a number. You could easily re-write this using a simple loop to avoid the recursion construct.
It cuts off the most right digit and moves on recursively with the rest of the number. (line 5)
If we have only one digit left (line 2), it is also added to the sum and the algorithm ends. (line 3)
In this example there is a if else condition so on the basis of input parameter there are 2 conditions '
-Firstly it checks in the if condition (n/10 == 0) .
-Consider your input as n=15.
now it checks if (n/10 == 0) i.e 15/10==0 which is false because 15/10=5 which is not equal to 0.
-As the condition is false it moves to else block where condition is to return
(n % 10 + calculate(n/10)
i.e. (15%10 +15/10)==5+1==6
-So the return is 6.
I am not getting errors at all in my code but it is NOT doing what I want it to - at all. I understand that there is another question related to divisibility to 3 or 5 but I do not think the question relates, as our coding is built completely different. I also find that this answer, this other answer, or even this answer are not helping me, either.
Anyway, I am trying to use a simple boolean expression to determine if an expression is true or not, then if it is true or not printing different lines. The intended look I would get is something like:
3 is divisible by 3
3 is not divisible by 5
4 is not divisible by 3
4 is not divisible by 5
5 is not divisible by 3
5 is divisible by 5
and so on...
However, I'm getting this:
3 is divisible by 3
3 is not divisible by 3
3 is divisible by 5
3 is not divisible by 5
and so on...
Initial problem can be found here. Right now I am just experimenting with the code, trying to get myself to a better understanding of Java. I wanted to start by knowing how to separate integers that are divisible by the numbers from integers that are not divisible by the numbers and I figured the best way to test this was to print the lines out. I do not know if I am going in the right direction at ALL here. Can anyone either give me pointers on the current code I have, or some hints, such as links to the corresponding Java commands that I will have to use for this program to work. If you post code that works, so I can see what I should be doing, that is fine too but please explain it to me, then. I don't want to just know what to type, I am trying to develop a solid foundation of programming problem-solving.
Sorry if this is a terrible question, I am EXTREMELY new to programming in general and am completely self-teaching. Give me some pointers, and I can most definitely change the question!
package multiplesof3and5;
public class InitialProgram {
public static void main(String[] args) {
// TODO Auto-generated method stub
int integer1;
integer1 = 0;
boolean divisibleby3 = (integer1 % 3) == 0;
boolean divisibleby5 = (integer1 % 5) == 0;
for( integer1=0; integer1<1000; integer1++){
if(divisibleby3 = true);{
System.out.println(integer1 + " can be divided by 3");}
if(divisibleby3 = false);{
System.out.println(integer1 + " cannot be divided by 3");}
if(divisibleby5 = true);{
System.out.println(integer1 + " can be divided by 5");}
if(divisibleby5 = false);{
System.out.println(integer1 + " cannot be divided by 5");
}
}
}
}
To start:
if(divisibleby3 = true);{
has a stray semicolon. Secondly, = is an assignment, but rather == should be used for comparison, and is not even necessary for booleans. Use this format:
if(divisibleby3){
and
if(!divisibleby3){ // if not divisible by three
Secondly,
boolean divisibleby3 = (integer1 % 3) == 0;
boolean divisibleby5 = (integer1 % 5) == 0;
need to be inside the loop, since otherwise they're only evaluated once (you only check if 0 is divisible by three and five and use the result of that check over and over again, instead of checking each integer).
Optionally, instead of using if/if pairs, you can just use if/else twice in each loop (if divisible by 3 print that it is, else print that it isn't; same for divisibility by five).
In the end, this is the code that will work:
public static void main(String[] args) {
for(int integer1 = 0; integer1 < 1000; integer1++){
boolean divisibleby3 = (integer1 % 3) == 0;
boolean divisibleby5 = (integer1 % 5) == 0;
if(divisibleby3) {
System.out.println(integer1 + " can be divided by 3");
} else {
System.out.println(integer1 + " cannot be divided by 3");
}
if(divisibleby5){
System.out.println(integer1 + " can be divided by 5");
} else {
System.out.println(integer1 + " cannot be divided by 5");
}
}
}
You're detemining your divisibility before you start to check it against numbers:
int integer1;
integer1 = 0;
boolean divisibleby3 = (integer1 % 3) == 0;
boolean divisibleby5 = (integer1 % 5) == 0;
for( integer1=0; integer1<1000; integer1++){
You need to continuously update your divisibility with each change of integer1, like so:
for( integer1=0; integer1<1000; integer1++){
boolean divisibleby3 = (integer1 % 3) == 0;
boolean divisibleby5 = (integer1 % 5) == 0;
Just noticed #hexafraction's answer:
You also need to compare statements with ==, right now you're just assigning the booleans to true or false, since you only use =
The issue in your code is that you never change your booleans.
They always stay the same, because they are only based on the initial integer1.
To fix this, simply move both of your boolean declarations into the for loop.
I am on mobile, so I can't write it down / check it, but I am pretty certain it'll work.
Best regards,
-Yuval Gat
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.