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);
}
Related
Ok in this method I am supposed to compute the factorial using only the evens. So for example if I inputed 7 for n I would expect 6*4*2 = 48. I am supposed to fix the code so it will work. I have tried for like an hour now and don't know what I am doing wrong. Here is my code:
int p07EvenFactorial(int n) {
if (n % 2 == 1) {
n--;
}
int fact = 1;
for (int i = n; i > 0; i--) {
fact = fact + 2 * i;
}
return fact;
}
how about
int p07EvenFactorial(int n) {
if (n % 2 == 1) {
n--;
}
int fact = 1;
for (int i = 2; i <= n; i = i + 2) {
fact = fact * i;
}
return fact;
}
How about this
public int fact(int n) {
if(n % 2 ==1){
n = n -1;
}
if(n == 0){
return 1;
} else {
return n*fact(n-2);
}
}
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
I'm doing this problem:
Write a program to check whether a given number is an ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.
Note that 1 is typically treated as an ugly number.
Here's my attempt:
public class Solution {
public boolean isUgly(int num) {
if (num == 1) {
return true;
}
for (int i = 7; i <= num / 2; i++) {
if (isPrimeFactor(i, num)) {
return false;
}
}
return true;
}
public boolean isPrimeFactor(int candidate, int num) {
return isPrime(candidate) && isFactor(candidate, num);
}
public boolean isPrime(int num) {
if (num == 2) {
return true;
}
if (num % 2 == 0) {
return false;
}
for (int i = 3; i <= Math.sqrt(num); i += 2) {
if (num % i == 0) {
return false;
}
}
return true;
}
public boolean isFactor(int candidate, int num) {
return (num % candidate == 0);
}
}
Unfortunately, it fails on test input -2147483648. It returns true when it should be false.
Any idea what I've done wrong?
You simply forgot the following emphasized condition:
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.
Therefore, you just need to add a check for negative numbers inside your isUgly method:
if (num <= 0) {
return false;
}
As a side-note, you could perhaps improve a little the performance by swapping the conditions inside isPrimeFactor and testing isFactor(candidate, num) && isPrime(candidate) instead of isPrime(candidate) && isFactor(candidate, num). This is because it is faster to determine whether a number is a factor of another than determining if a number is a prime number.
I could propose a different but a lot faster solution O(logn) for this problem:
public static boolean isUgly(int num) {
if (num < 1) return false;
int temp;
do {
temp = num;
if (num % 2 == 0) num /= 2;
if (num % 3 == 0) num /= 3;
if (num % 5 == 0) num /= 5;
} while (temp != num);
return num == 1;
}
or an even faster approach in terms of modular checks (by splitting the do while loop):
public static boolean isUgly(int num) {
if (num < 1) return false;
int temp;
do {
temp = num;
if (num % 2 == 0) num /= 2;
} while (temp != num);
do {
temp = num;
if (num % 3 == 0) num /= 3;
} while (temp != num);
do {
temp = num;
if (num % 5 == 0) num /= 5;
} while (temp != num);
return num == 1;
}
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);
I'm having some trouble in completing this factor generator from my programming class. It's supposed to take a number, and print out all the factors using the nextFactor method. When I set the number to factor to let's say 150, it prints out "1 2 3 5", where it's supposed to print "2 3 5 5". So, where should I go from here? I've looked at Java - Factor Generator program nextfactor method, but it didn't awnser any of my inqueries
public class FactorGenerator
{
//user inputs int from scanner in FactorTester class
public FactorGenerator(int i)
{
num = i;
}
//Checks to see if num can be factored, but does not factor it.
//Goes through all possible factors of num and returns true if the remainder == 0
public boolean hasMoreFactors()
{
for(int i = 1; i < num; i++)
{
//check if the remainder is anything other then 0
if(num % i == 0)
{
return true;
}
}
return false;
}
//Actually factors num and prints out the factor at the end of every loop.
public void nextFactor()
{
for(int i = 1; i < num; i++)
{
//check if the remainder is anything other then 0
if(num % i == 0)
{
System.out.println(i);
num /= i;
}
}
System.out.println("Done.");
}
private int num;
}
try this factors can duplicate so you need to loop until you have extracted all the instances of that factor
public void nextFactor()
{
for(int i = 2; i <= num; i++)
{
//check if the remainder is anything other then 0
while (num >= i && num % i == 0)
{
System.out.println(i);
num /= i;
}
}
System.out.println("Done.");
}
an alternative way is to do the increment in the body of the loop
public void nextFactor()
{
for(int i = 2; i <= num;)
{
//check if the remainder is anything other then 0
if (num % i == 0)
{
System.out.println(i);
num /= i;
} else {
i++;
}
}
System.out.println("Done.");
}
For starters, it will always print out 1 because any integer / 1 will always have remainder of zero. You can start i from 2 instead of 1 in your for if you want to skip 1.
I'd suggest something like this: (note this is based in part on BevynQ's answer below):
for(int i = 2; i <= num; i++){
while (num >= i && num % i == 0) {
System.out.println(i);
num /= i;
}
}