Every prime number is in the form of 6k+1 or 6k-1. In order to check if a number is prime or not we can use the below algorithm. I have seen programs that are written based on these algorithms.
public boolean isPrime(int n)
{
if (n <= 1) return false;
if (n <= 3) return true;
if (n%2 == 0 || n%3 == 0) return false;
for (int i=5; i*i<=n; i=i+6)
if (n%i == 0 || n%(i+2) == 0)
return false;
return true;
}
But I don't understand what would have been the problem if we had written code in the following manner:
public boolean isPrime(int number){
boolean primeFlag = false;
if(number == 0 || number ==1){
return primeFlag;
}
if(number == 2 || number == 3){
primeFlag = true;
}
if((number+1)%6 == 0){
primeFlag = true;
}
if((number-1)%6 == 0){
primeFlag = true;
}
return primeFlag;
}
By this we can reduce the time complexity to O(1) compared to O(root(n)). Please let me know if am heading towards wrong direction.
It is correct to say that every prime (except for 2 and 3) has a remainder of 1 or 5 when divided by 6 (see this page for a deeper explanation). However, the opposite is not true. Not every number that has a remainder of 1 or 5 when divided by 6 is a prime.
Take 35 for example. It has a remainder of 5 when divided by 6, however it is not a prime (35 = 5 x 7).
Related
This was asked during my interview. I have to write a program to find all the prime numbers which are having only odd digits in them for the given range.
Eg: 31 is a prime number having only odd digits in it 3 & 1.
Eg: 23 is a prime number but it is not having odd digits in it, because it has digit 2.
Now I have one more constraint, to my program, I will pass a variable called temp.
Now if this temp is 1 then I should find the primes, with digits containing only <= 5.
If this temp is 2 then I should find the primes, with digits containing only >= 5.
Sample Input:
If the start position is 30 & end position is 40 with temp value as 1. The possible prime numbers are 31, 37 in the 30 to 40.
31 prime has digits 3 & 1 => so these digits are <= 5.
Now if my temp input data is `1` then the program should return me 1.
If suppose my temp input data is `2` then the program should return me 0.
37 is a prime number with digits 3 & 7. Here 3 <=5 and 7 >= 5. So we should not count this prime number as it will not fall under any category defined for my temp variable.
So for input values start=30, end = 40, temp = 1 output should be 1.
(because of prime number 31).
I have come up with the below code:
public static int process(int start, int end, int temp) {
List<Integer> matching = new ArrayList<>();
// loop from start to end
for (int i = start; i <= end; i++) {
// 0 & 1 are not primes so skip them
if (i == 1 || i == 0) {
continue;
}
// Check if the number is a prime
if (isPrime(i)) {
// Get the digits of that prime number Eg: 31 has digits 3 & 1
List<Integer> nums = new ArrayList<>();
buildDigits(i, nums);
// Codition to check if we need to consider this prime or not in our result.
boolean flag = true;
for (Integer num : nums) {
// The prime number is has an even digit, so discard it.
if (num % 2 == 0) {
flag = false;
break;
}
// The prime has a digit > 5 where as the restriction falls under step 1, so discard
if (temp == 1 && num > 5) {
flag = false;
}
// The prime has a digit < 5 where as the restriction falls under step 2, so discard
if (temp == 2 && num < 5) {
flag = false;
}
}
// Get the required primes
if (flag) {
matching.add(i);
}
}
}
// Return their count
return matching.size();
}
// Find out all digits in a given number, and put them in the list called nums
public static void buildDigits(int num, List<Integer> nums) {
if (num / 10 > 0) {
buildDigits(num / 10, nums);
}
nums.add(num % 10);
}
// This just finds out if the given input is prime or not
public static boolean isPrime(int n) {
if (n <= 1) {
return false;
}
if (n <= 3) {
return true;
}
if (n % 2 == 0 || n % 3 == 0) {
return false;
}
for (int i = 5; i * i <= n; i = i + 6) {
if (n % i == 0 || n % (i + 2) == 0) {
return false;
}
}
return true;
}
I above code, I have used this link as basis for isPrime to find prime or not.
When I used this code in my interview it cleared only 3 test cases out of 8. The test cases are hidden, I was not clear for what inputs this logic failed.
I have gone through this code in debug mode also, but I was not able to find where I made mistake.
Convert the following without if/loops. You can still use recursion, &&, || etc...
public boolean mystery(int n){
if(n == 0){
return false;
}
if(n%10 == 7){
return true;
}
return mystery(n/10)
}
I would like hints.
But I've been experimenting around.
We know that true && false == false and only true && true == true
So we must have that
return (n%10 == 7) && ....
Then for the second part, we could either get true or false, and if the second part is true, then our first part being true will result in everything being true, so I am thinking.
return (n%10 == 7) && ...
But I am thinking an issue might be that if n%10 isnt 7 right off that bat everything is false.
In my view, the ternary operator is still pretty much an 'if' statement - but that becomes a semantic debate. You can avoid using it entirely.
return (n % 10 == 7) || (n != 0 && mystery(n/10));
There are many ways: but to give you a start:
if(n == 0){
return false;
}
if(n%10 == 7){
return true;
}
return mystery(n/10)
}
is equivalent to
return n==0 ? false : n%10==7 ? true : mystery(n/10);
is equivalent to
return n!=0 ? n%10==7 ? true : mystery(n/10): false;
is equivalent to
return n!=0 && n%10!=7 ? mystery(n/10) : n!=0;
Was an interesting activity to solve. Solution below with proof of testing till 10k. mystery2 is the method of interest for you.
How I got the solution:
Started printing the results from 0 to 100 and identify the pattern - found the ones starting or ending with 7 would return true and all others false. The first if block which compares with zero is actually encountered by all the numbers which do not qualify reminder 7 rule in any position. Thus, reminder 7 is the only condition to get true result and everything else would enter recursion until it becomes 0 after the unit's position is complete. Equating to 0 is required as we should have a condition that ends the recursion (or ends in StackOverflowException).
public static void main(String[] args) {
for(int i = 0 ; i<=10000; i++){
if(mystery(i) != mystery2(i)){
System.out.println("Mismatch... "+i);
}
}
}
static boolean mystery(int n) {
if (n == 0) {
return false;
}
if (n % 10 == 7) {
return true;
}
return mystery(n / 10);
}
static boolean mystery2(int n) {
return n % 10 == 7 || (n != 0 && mystery2(n / 10));
}
I am trying to solve this : Given an integer, return 1 if the number is between -5 and 5 exclusive and/or if it is an odd integer. If neither properties apply, return 0.
Here is what I have tried:
int rangeOrOdd(int val) {
if (val < 5)
return 1;
else if (val > 5)
return 1;
else if ((val%2)!=0)
return 0;
else
return 0;
}
The problem is that you are checking the different conditions individually. For instance, as soon as your number is smaller than 5, you return 1, which is wrong, because you would then return 1 for numbers like -1000.
Also, you are returning 0 for an odd number. You were supposed to return 1 in that case.
You have to combine your conditions using ANDs (&&) and ORs (||).
Here is a one liner that combines the different conditions correctly:
return ((val < 5 && val > -5) || val % 2 == 1) ? 1 : 0;
And if you don't like it in one line, you can always split it like this (but it's the same thing):
if ((val < 5 && val > -5) || val % 2 == 1) {
return 1;
} else {
return 0;
}
Coding bat is a website to test the candidate's logic and reasoning abilities using JAVA or Python. I am trying the following problem and am unable to proceed:
Given a non-negative number "num", return true if num is within 2 of a multiple of 10. Note: (a % b) is the remainder of dividing a by b, so (7 % 5) is 2. See also: Introduction to Mod
nearTen(12) → true
nearTen(17) → false
nearTen(19) → true
.
The code I have written is :
{
public boolean nearTen(int num) {
if (num==10 || num==1){
return true;}
else if (num<10){
return false;}
else if ((num+2)%10==0 || ((num-2)%10==0)){
return true;}
else if ((num+1)%10==0 || ((num-1)%10==0)){
return true;}
else{
return false;}
}
}
Can anyone of you please tell my mistake so that I can improve on the same?
You have to check if the modulo of the given number is either less that or equal to 2 (<= 2), or greater than or equal to 8 (>= 8).
You don't have to check for any special values, since there aren't any, they respond to the general logic of the question.
public boolean neatTen (int num) {
if (num%10 <= 2 || num%10 >= 8) {
return true;
} else {
return false;
}
}
If you had to take into account negative values, you would have to use Math.abs() to make the number positive, but that's a very small change to the code.
If you want to have it as a one-liner:
return (num%10 <= 2) ? true : (num%10 >= 8) ? true : false ;
Return true if remainder after dividing by 10 is 0, 1, 2, 8 or 9.
public boolean nearTen (int num) {
if (num%10 <= 2 || num%10 >= 8)
return true;
return false;
}
If I had understood the question right then you just need to use mod(%) and check if the reminder is <= 2 or >= 8.
public static boolean nearTen(int num) {
if (num==10 || num==1){
return true;
}
else if (num<10 && 10-num<2){
return true;
}
else if (num%10<=2 || num%10>=8){
return true;
}
else{
return false;
}
}
I read a book about challenges in Java, and it gives the next question:
create a function, which get a number as argument, and detect if number is a multiple of 7 or contains the number 7.
The signature is: public boolean find7(int num)
I create this function, when the number is between 0 to 99, by the next condition:
if (num mod 7 == 0 || num / 10 ==7 || num mod 10 == 7)
return true;
But what with number which is greater than 99? like 177, or 709? How can I detect it?
It's probably best to leave strings out of this:
public static boolean check(final int n) {
int m = Math.abs(n);
while (m > 0) {
if (m % 10 == 7)
return true;
m /= 10;
}
return n % 7 == 0;
}
The while-loop checks each digit and tests if it is 7; if it is, we return true and if it isn't, we continue. We reach the final return statement only if none of the digits were 7, at which point we return whether the number is a multiple of 7.
if (num % 7 ==0 || ("" + num).contains("7") ){
return true;
}
You can extend your approach to numbers above 100 like this:
public boolean find7(int num) {
// support for negative integers
num = Math.abs(num);
// check if num is a multiple of 7
if (num % 7 == 0) {
return true;
}
// check to see if num contains 7
while (num > 1) {
// if the last digit is 7, return true
if (num % 10 == 7) {
return true;
}
// truncate the last digit
num /= 10
}
// the number is not a multiple of 7 and it does not contain 7
return false;
}
You can do the following
if(Integer.toString(num).contains("7") || ...){
}
As far as checking if the number is divisible by 7, you're fine.
If you want to check if it contains the 7 digit, I think the easiest approach would be to treat the number as a String:
public boolean find7(int num) {
// check if it's a multiple of 7:
if (num % 7 == 0) {
return true;
}
// if it's not, check if it contains the character 7:
return String.valueOf(num).contains("7");
}
For detecting if number is multiple of 7:
boolean isMultiple = x % 7 == 0
For detecting digit:
Convert it to String and use String.contains()
or
Create digit List like this:
private List<Integer> getDigitList(int number){
List<Integer> list = new ArrayList<Integer>();
int leftover = number;
while (leftover != 0){
int result = leftover % 10;
leftover = (leftover - result)/10;
list.add(result)
}
assert leftover == 0;
return list;
}