Once I took from the user 10 numbers and placed them in an array of size 10, I want to check for each number in the array if it is prime or not and count how many prime numbers there is. Here is what I tried to do:
int count=0;
for(int r=0;r<10;r++) {
for(int t=2; t < array[r];t++) {
if(array[r] % t != 0) {
count++;
}
}
}
array[r] is already filled with numbers at this point, so all I need to do is to check for each number if it is prime or not.
Here is another way you can check for prime numbers. It does not increment by 1, so it is faster.
int count=0;
for(int r=0;r<10;r++){
if (isPrime(array[r])) count++;
}
And the method:
public static boolean isPrime(int n) {
if(n < 2) return false;
if(n == 2 || n == 3) return true;
if(n%2 == 0 || n%3 == 0) return false;
int sqrtN = (int)Math.sqrt(n)+1;
for(int i = 6; i <= sqrtN; i += 6) {
if(n%(i-1) == 0 || n%(i+1) == 0) return false;
}
return true;
}
int a[] = {0,1,2,3,4,5,6,7,8,9};
int count=a.length;
boolean flag=true;
for(int i=0;i<a.length;i++)
{
for(int j=2;j<a[i];j++)
{
if(a[i]%j==0)
{
flag=false;
break;
}
}
if(flag==false)
{
count--;
}
}
System.out.println(count);
Related
I'm doing the program for SPOJ.com taks which should recognize Prime number. Unfortunately this SPOJ taks is in Polish language, hence I will try to translate what should be the input and outpu expectation:
Input:
n - the number of tests n <100000, in the next lines n numbers from the interval [1..10000]
Output:
For each number of the word "YES", if this number is prime. Word: "NO", otherwise.
Example:
Input:
3
11
1
4
Output:
YES
YES
NO
I wrote following code whcih during the test works perfectly fine. Unfortunately when I'm trying to submit this code on SPOJ webpage it is constantly returning me error "
runtime error (NZEC)" Can someone advise how I can improve it?
Scanner in = new Scanner(System.in);
int n = in.nextInt();
if(1<=n&& n<=100000){
for(int i = 0; i<n+1; i++){
int v = in.nextInt();
if(1<=v&&v<=10000){
if(isPrime(v) == true){
System.out.println("YES");
}
if(isPrime(v) == false){
System.out.println("NO");
}
}
}
}
}
private static boolean isPrime(int v) {
if (v < 2) return true;
if (v == 2) return true;
if (v % 2 == 0) return false;
for (int i = 3; i * i <= v; i += 2)
if (v % i == 0) return false;
return true;
}
Have you learnt Sieve Method for Prime numbers.
Check here you will find the better solution.
public class PrimeSieve {
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
// initially assume all integers are prime
boolean[] isPrime = new boolean[n+1];
for (int i = 2; i <= n; i++) {
isPrime[i] = true;
}
// mark non-primes <= n using Sieve of Eratosthenes
for (int factor = 2; factor*factor <= n; factor++) {
// if factor is prime, then mark multiples of factor as nonprime
// suffices to consider mutiples factor, factor+1, ..., n/factor
if (isPrime[factor]) {
for (int j = factor; factor*j <= n; j++) {
isPrime[factor*j] = false;
}
}
}
// count primes
int primes = 0;
for (int i = 2; i <= n; i++) {
if (isPrime[n]) primes++;
}
System.out.println("The number of primes <= " + n + " is " + primes);
}
}
You should check all numbers from 2 to n, to see if the number isPrime or not.
Code
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
for(int i = 0; i < n ; i++) {
int v = in.nextInt();
if (v >= 1 && v < 10000) {
if (isPrime(v) == true) {
System.out.println("YES");
}
if (isPrime(v) == false) {
System.out.println("NO");
}
}
}
}
private static boolean isPrime(int v) {
for(int i=2;i<v;i++) {
if(v%i==0)
return false;
}
return true;
}
}
I hope this helps you.
I'm not sure why my ct is not going all the way to 100 even though I clearly set it to go until it reaches 100.
public class PalindromicPrime
{
public static void main(String [] args)
{
int ct = 0;
while(ct < 100)
{
if(isPalindrome(ct) && isPrime(ct))
{
if(ct % 10 != 0)
{
System.out.print(ct + " ");
}
else
{
System.out.print("\n");
}
}
ct++;
}
public static boolean isPalindrome(int p)
{
int palindrome = p;
int reverse = 0;
while (palindrome != 0)
{
int remainder = palindrome % 10;
reverse = reverse * 10 + remainder;
palindrome = palindrome / 10;
}
if (p == reverse)
{
return true;
}
return false;
}
I'm assuming my isPrime code is wrong since I'm getting a 4 in my output. What's wrong with this method?
public static boolean isPrime(int p)
{
for(int i = 2; i < p/2; i++)
{
if(p % i == 0)
{
return false;
}
}
return true;
}
}
First change you should do in your method isPrime() is change this line
for(int i = 2; i < p/2; i++)
to
for(int i = 2; i <= p/2; i++) // you can easily find the reason why it is necessary(=)
And also you are printing palindromic numbers less than 100 which are prime,not first 100 palindrome numbers, if you want to print first 100 palindrome numbers you can take another counter which will keep track of the numbers printed.
You can modify your main method like this:
public static void main(String [] args)
{
int ct = 0,n=0; // n to count numbers printed/found
while(n < 100) // change the condition to check n<100
{
if(isPalindrome(ct) && isPrime(ct))
{
System.out.print(ct + " ");
if(n % 10 == 0)
{
System.out.println();
}
n++; // incementing n after a number is found!
}
ct++;
}
}
Your palindrome method is fine. It's your isPrime method that's not working because to check if a number is prime, you're supposed to test factors up to the square root of the number. So a simple change in the condition should do it,
public static boolean isPrime(int p)
{
for(int i = 2; i <= Math.sqrt(p); i++)
{
if(p % i == 0)
{
return false;
}
}
return true;
}
}
Change your isPrime function to following (replace < with <= as 4/2 is 2 and loop will not run at all for p=4):
public static boolean isPrime(int p) {
for (int i = 2; i <= p / 2; i++) {
if (p % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
int ct = 2;
int count = -1;
while (count < 99) {
if (isPalindrome(ct) && isPrime(ct)) {
count++;
if (count % 10 == 0) {
System.out.print("\n" );
}
System.out.print(ct + " ");
}
ct++;
}
}
The only numbers that are palindrome and prime and less than 100 are:
1 2 3 5 7 11
Try changing the value of 100 to 102. Then you get the following output as 101 is the next palindromic prime after 11:
1 2 3 5 7 11 101
The question is about Solving this problem from codingBat in Java.
Problem Statement:
Given an array of ints, return true if every 2 that appears in the array is next to another 2.
twoTwo({4, 2, 2, 3}) → true
twoTwo({2, 2, 4}) → true
twoTwo({2, 2, 4, 2}) → false
First of all going by the problem statement that every 2 that appears in the array is next to another 2. then
do you think as suggested the outcome for the first inputs shown above
should be true?
twoTwo({4, 2, 2, 3}) → true
Because as I see it it the first 2 itself that appears in the array is next to 4 not 2
am I confused or it's a wrongly stated question? I had to grapple with the problem to somehow get the right code to crack the problem as below but it seems a hotch potch:
public boolean twoTwo(int[] nums) {
if(nums.length==0)
{
return true;
}
if(nums.length==1)
{
return !(nums[0]==2);
}
if((nums.length==2))
{
if((nums[1]==2)&&(nums[0]==2))
return true;
else
return false;
}
for(int i=0;i+2<nums.length;i++)
{
if((nums[i]!=2)&&(nums[i+1]==2)&&(nums[i+2]!=2))
return false;
}
if((nums[nums.length-2]!=2)&&(nums[nums.length-1]==2))
return false;
return true;
}
Any efficient alternate solutions are welcome.
Thanks!
Here's how I would do it. It's a bit easier to follow I think:
public boolean twoTwo(int[] nums)
{
for (int i=0; i<nums.length; i++)
{
if (nums[i] != 2)
continue;
if (i >= 1 && nums[i-1] == 2)
continue;
if (i < (nums.length-1) && nums[i+1] == 2)
continue;
return false;
}
return true;
}
The solution I got to the problem is below:
public boolean twoTwo(int[] nums) {
final int length = nums.length;
for (int i = 0; i < length;){
int count = 0; // Used to count following 2's
while(i < length && nums[i++] == 2){
count++;
}
if(count == 1){ // No adjacent 2's! Set doesn't work.
return false;
}
}
return true; // Didn't come across a lone 2
}
The way that I handle this, is that I count all the adjacent 2's. If the count is not 1, we are good. This means that there was either no 2 at that index, or a group of 2's was present. This holds, since we traverse the array in a single direction.
A good thing about this solution is that it will work for an array of any size. Note that it would have a linear complexity, even though 2 loops are present. They both just traverse using the same index value, only ever sweeping over the array once.
If at any time we find a 2, then check the following only to find there are 0 following 2's (denoted by count), we return false.
public boolean twoTwo(int[] nums) {
for (int i=0; i<nums.length; i++) {
if(nums[i] == 2) { //If current number is 2
if (
// if prev or next is not 2 return true
!(i-1>=0 && nums[i-1] == 2) &&
!(i+1<nums.length && nums[i+1] == 2)
) { return false; }
}
}
return true;
}
For the sake of simplicity and clean code, this code forces the check
i-1>=0 and i+1<nums.length in every iteration.
This can be avoided by iterating from (1...nums.length-1) and checking the edge cases separately.
I know this is an old question, but I came up with a new solution. Short, and with no complicated conditionals.
public boolean twoTwo(int[] nums) {
int position = -2;
boolean result = true;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 2) {
result = position == i - 1;
position = i;
}
}
return result;
}
Next to means either before or after. Loop through each number and check the values before and after to see if there's an adjacent 2. The special cases are when you're checking the 1st and last element because there won't be an element before or after to check.
public boolean twoTwo(int[] nums) {
if(nums.length == 1 && nums[0] == 2)
return false;
for(int i = 0; i < nums.length; i++) {
if(nums[i] == 2) {
if(i == 0) { // check the next element
if(nums[i+1] != 2)
return false;
}
else if(i == (nums.length - 1)) { // check the previous element
if(nums[i-1] != 2)
return false;
}
else { // check both
if(nums[i+1] != 2 && nums[i-1] != 2)
return false;
}
}
}
return true;
}
Here is mine solution to two two's problem. I think my solution is clear i.e. understandable.
package codingbat.array2;
public class TwoTwo
{
public static void main(String[] args)
{
}
public boolean twoTwo(int[] nums)
{
boolean twoTwo = true;
for (int i = 0; i < nums.length; i++)
{
if (2 == nums[i])
{
if (i > 0 && 2 == nums[i - 1]
|| nums.length > i+1 && 2 == nums[i+1])
{
twoTwo = true;
i++;
}
else
{
twoTwo = false;
break;
}
}
}
return twoTwo;
}
}
public boolean twoTwo(int[] nums) {
for(int i = 0 ; i < nums.length; i++ ) {
int count = 0;
if(nums[i] == 2 ) {
while(i+1 < nums.length && nums[i+1] == 2 ) {
count ++;
i++;
}
if (count == 0 ) {
return false;
}
}
}
return true;
}
public boolean twoTwo(int[] nums) {
for(int i = 0;i<nums.length;i++)
if(nums[i]==2 && !isTwoBeforeOrAfter(nums,i))
return false;
return true;
}
private boolean isTwoBeforeOrAfter(int[] nums,int i){
return i+1<nums.length && nums[i+1]==2 || i-1>=0 && nums[i-1]==2;
}
public boolean twoTwo(int[] nums) {
float two = 0;
double count = 0;
for (int i = 0; i < nums.length; i++) {
if (i < nums.length - 2 && nums[i] == 2 && nums[i + 1] == 2 && nums[i + 2] == 2) {
return true;
}
if (i < nums.length - 1 && nums[i] == 2 && nums[i + 1] == 2) {
count++; //count the pair
}
if (nums[i] == 2) {
two++;
}
}
return ((count * 2) == two);
//each pair contain 2 ,two"s .so pair*2=total two counts
//count
}
public boolean twoTwo(int[] nums) {
boolean two = false;
boolean result = true;
for (int i=0; i<nums.length; i++) {
if (nums[i] == 2) {
if (two) {
result = true;
} else {
result = false;
}
two = true;
} else {
two = false;
}
}
return result;
}
Here's my solution. Enjoy.
public boolean twoTwo(int[] nums)
{
//If the length is 2 or more
if (nums.length >= 2)
{
//If the last char is a 2, but the one before it is not a char, we return false;
if (nums[nums.length - 1] == 2 && nums[nums.length - 2] != 2)
{
return false;
}
//If larger than three, we create a for loop to test if we have any 2s that are alone.
if (nums.length >= 3)
{
for (int i = 1; i < nums.length-1; i++)
{
//If we find a two that is alone, we return false;
if ((nums[i] == 2) && (nums[i-1] != 2 && nums[i+1] != 2))
{
return false;
}
}
}
//If we don't return false, we return true;
return true;
}
//If we have less than two characters, we return true if the length is 0, or \
//One the one number there is not a 2.
else
{
return ((nums.length == 0) || !(nums[0] == 2));
}
}
public boolean twoTwo(int[] nums) {
int len = nums.length;
Boolean check = false;
int count = 0;
for(int i=0; i<len ; i++){
if(nums[i]==2){
count++;
if((i<len-1 && nums[i+1]==2) || (i>0 && nums[i-1]==2)) check = true;
else check = false;
}
}
if(count==0) check = true;
return check;
}
public boolean twoTwo(int[] nums) {
int count = 0;
for (int i = 0; i < nums.length; i++)
if (nums[i] == 2) count++;
else if (count == 1) return false;
else count = 0;
return count != 1;
}
Every time we encounter a 2, we increase the counter of consecutive 2s.
When it's not a 2 — but the counter indicates that there was a single 2 before it —, we know we've found a lonely 2.
Otherwise the search continues, resetting the 2-counter.
easy to understand)
static boolean twoTwo(int[] nums) {
int len = nums.length;
boolean result = true;
boolean found = false;
for(int i=0; i<len; i++){
//if it not 2, no meaning to go true other if-s
if(nums[i] !=2) {found = false; continue;}
// if current element is 2 and found is true(last element is 2)
if(nums[i] ==2 && found) result = true;
// if current element is 2, but last element not
if(nums[i] ==2 && !found){
found = true;
result = false;
}
}
return result;
}
This might be easier to follow if the other suggestions confuse you..
public boolean twoTwo(int[] nums) {
int len = nums.length;
if(len == 0) return true; // no 2's to worry about
if(len == 1) return nums[0] != 2; // make sure it's not a single 2
for(int i = 1; i < len -1; i++){ // loop for each except edge cases
if(nums[i] == 2 && nums[i-1] != 2 && nums[i+1] != 2) return false; // check surrounding
}
if(nums[len - 1] == 2) return nums[len - 2] == 2; //if last num is 2 check for 2 before it
return true; // made it here it's true
}
that one was tough for me... here's mine:
public boolean twoTwo(int[] nums) {
boolean two = false, res = true;
for (int i : nums) {
if (i == 2) {
if (two)
res = true;
else {
two = true;
res = false;
}
} else {
two = false;
}
}
return res;
}
One more alternative. Here is the main idea:
Convert array into String. Add a character different from "2" at the beginning and end of the string, to avoid going out of bounds.
Look for standalone "2" - if element of the string is equal to 2, check whether chars immediately before and after are also equal to "2". If they are it means that not all "2" are adjacent, and therefore method returns false.
public boolean twoTwo(int[] nums) {
// convert array to string
String text = "";
for (int i = 0; i < nums.length; i++) {
text += String.valueOf(nums[i]);
}
text = " " + text + " ";
// find standalone "2"
for (int i = 1; i < text.length() - 1; i++) {
if (text.charAt(i) == '2' && text.charAt(i - 1) != '2' && text.charAt(i + 1)
!= '2') {
return false;
}
}
return true;
}
public static boolean isPrime(int number)
{
boolean result = true;
if (number == 0)
{
result = false;
}
for (int i=2; i < number/2; i++)
{
if (number % i == 0)
{
result = false;
}
}
return result;
}
Any ideas why when int number = 4, the result returns as true? What can I do to fix this? I am happy with the code I have but why does 4 return as true?
for (int i=2; i < number/2; i++)
If you enter 4 here, it will never enter the loop because
2 < 4 / 2
never equates to true (2 is not smaller than 2).
Instead, use <=.
Effective way how to do this method is :
(sorry for duplication, but after some time, someone can find this topic and not previous one)
public static boolean isPrime(int number) {
//Everything less or equal 1 is not prime number
if (number <= 1) {
return false;
}
//2 is very special case, so I check it separately
if (number == 2) {
return true;
}
//This will help me rid off all even numbers
if (number % 2 == 0) {
return false;
}
//It is important to count the sqrt before using it in for-loop condition.
//If you use it in for-loop condition, it will be counted every single iteration.
int square = (int) Math.sqrt(number);
//I already checked %2, so now I need to check only odd numbers
for (int i = 3; i <= square; i += 2) {
if (number % i == 0) {
//If I find one number, I do not have to continue
return false;
}
}
return true;
}
Your for loop never executes when number = 4. This is because:
for (int i=2; i < number/2; i++)
Executes when i == 2 and i < 2. That will never happen if number == 4, because then it'll be i < 4 / 2 which is i < 2. To solve this, remove the /2 or do something else... not quite sure what you're going for there.
When number==4 the boolean condition of the first if is false and the first evaluation of the for condition is also false. So the result is the value you used to initialize result (true).
Also, you might want to return the result instead of storing it in a variable because the code will continue to execute after the first conditional... So here is the working solution:
public static boolean isPrime(int number) {
if (number <= 1) { /* Since 1 isn't technically a prime number */
return false;
}
for (int i=2; i <= number/2; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
Another solution:
public static boolean isPrime(int number) {
if (number < 2) {
return false;
}
for (int i=2; i <= (int)Math.sqrt(number); i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
Better and faster version of your code:
public static boolean isPrime(int number) {
if (number <= 1) {
return false;
}
for (int i=2; i*i <= number; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
It is possible to count the number of zeros in an integer through a recursive method that takes a single int parameter and returns the number of zeros the parameter has.
So:
zeroCount(1000)
Would Return:
3
You can remove the last digit from an integer by doing: "12345 / 10" = 1234
You can get the last digit from an integer by doing: "12345 % 10" = 5
This is what I have so far:
public static int zeroCount(int num)
{
if(num % 10 == 0)
return num;
else
return zeroCount(num / 10);
}
Does anyone have any suggestions or ideas for helping me solve this function?
public static int zeroCount(int num)
{
if(num == 0)
return 0;
if(num %10 ==0)
return 1 + zeroCount(num / 10);
else
return zeroCount(num/10);
}
this would work
Run through your code in your head:
zeroCount(1000)
1000 % 10 == 0, so you're going to return 1000. That doesn't make sense.
Just pop off each digit and repeat:
It sounds like homework, so I'll leave the actual code to you, but it can be done as:
zeroes(0) = 1
zeroes(x) = ((x % 10 == 0) ? 1 : 0) + zeroes(x / 10)
Note that without the terminating condition, it can recurse forever.
There are three conditions here:
1. If number is single digit and 0 , then return 1
2. If number is less than 10 i.e. it is a number 1,2,3...9 then return 0
3. call recursion for zeros(number/10) + zeros(n%10)
zeros(number){
if(number == 0 ) //return 1
if(number < 10) //return 0
else
zeros(number/10) + zeros(number%10)
}
n/10 will give us the n-1 digits from left and n%10 gets us the single digit.
Hope this helps!
Check this out for positive integers:
public static int zeroCount(int number) {
if (number == 0) {
return 1;
} else if (number <= 9) {
return 0;
} else {
return ((number % 10 == 0) ? 1 : 0) + zeroCount(number / 10);
}
}
it is a simple problem and you don't need to go for recursion
I think a better way would be converting the integer to a string and check for char '0'
public static int zeroCount(int num)
{
String s=Integer.toString(num);
int count=0;
int i=0;
for(i=0;i<s.length;i++)
{
if(s.charAt(i)=='0')
{
count++;
}
}
return count;
}
You have to invoke your recursive function from both if and else. Also, you were missing a Base Case: -
public static int zeroCount(int num)
{
if(num % 10 == 0)
return 1 + zeroCount(num / 10);
else if (num / 10 == 0)
return 0;
else
return zeroCount(num / 10);
}
import java.util.*;
public class Count
{
static int count=0;
static int zeroCount(int num)
{
if (num == 0){
return 1;
}
else if(Math.abs(num) <= 9)
{
return 0;
}
else
{
if (num % 10 == 0)
{ // if the num last digit is zero
count++;
zeroCount(num/10);
} // count the zero, take num last digit out
else if (num%10 !=0){
zeroCount(num/10);
}
}
return count;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Input: ");
int num = sc.nextInt();
System.out.println("Output: " +zeroCount(num));
}
}
public static int count_zeros(int n)
{
if(n<=9)
{
if(n==0)
{
return 1;
}
else
{
return 0;
}
}
int s=n%10;
int count=0;
if(s==0)
{
count=1;
}
return count+count_zeros(n/10);
}
int countZeros(int n){
//We are taking care of base case
if(n<=9){
if(n==0){
return 1;
}
else
{
return 0;
}
}
int last=n%10; //last element of number for e.g- 20403, then last will give 3
int count=0; //Initalsizing count as zero
if(last==0){ //We are checking either the last digit is zero or not if it will
will update count from 0 to 1
count=1;
}
return count+countZeros(n/10); //Recursive call
}
int check(int n){
if(n==0)
return 1;
return 0;
}
int fun(int n)
{
if(n/10==0)
{
if(n==0){
return 1;
}
else{
return 0;
}
}
return check(n%10)+fun(n/10);
}
Check this out, this is the solution I came up with.
int countZeros(int input){
//base case
if(input == 0){
return 1;
}
int count = 0;
int lastDigit = input%10;
if(lastDigit == 0){
count = 1;
}
//calc the smallInput for recursion
int smallInput = input/10;
//set smallAns = 0, if i/p itself is not 0 and no 0 is present then return smallAns = 0
int smallAns = 0;
//recursion call
if(smallInput != 0){
smallAns = countZerosRec(smallInput);
}
//if we get lastDigit = 0 then return smallAns + 1 or smallAns + count, else return smallAns
if(lastDigit == 0){
return smallAns+count;
}
else{
return smallAns;
}}
You know that x % 10 gives you the last digit of x, so you can use that to identify the zeros. Furthermore, after checking if a particular digit is zero you want to take that digit out, how? divide by 10.
public static int zeroCount(int num)
{
if(num == 0) return 1;
else if(Math.abs(num) < 9) return 0;
else return (num % 10 == 0) ? 1 + zeroCount(num/10) : zeroCount(num/10);
}
I use math.Abs to allow negative numbers, you have to import java.lang.Math;
static int cnt=0;
public static int countZerosRec(int input) {
// Write your code here
if (input == 0) {
return 1;
}
if (input % 10 == 0) {
cnt++;
}
countZerosRec(input / 10);
return cnt;
}
CPP Code using recursion:
int final=0;
int countZeros(int n)
{
if(n==0) //base case
return 1;
int firstn=n/10;
int last=n%10;
int smallop=countZeros(firstn);
if(last==0)
final=smallop+1;
return final;
}
int countZeros(int n)
{
if(n==0)
{
return 1;
}
if(n<10) // Needs to be java.lang.Math.abs(n)<10 instead of n<10 to support negative int values
{
return 0;
}
int ans = countZeros(n/10);
if(n%10 == 0)
{
ans++;
}
return ans;
}
public static int countZerosRec(int input){
// Write your code here
if(input == 0)
return 1;
if(input <= 9)
return 0;
if(input%10 == 0)
return 1 + countZerosRec(input/10);
return countZerosRec(input/10);
}