Homework assignment: I've been asked to create a method that will count all the odd numbers from 1 to value assigned to variable but it has to be with a while loop.
I've been using modulus to try and determine whether or not it's even or odd. I've tried identifying odd numbers and then just using + 2. I suspect it's a simple logic error I don't quite see.
public static void sumOddNumber(int number){
int counter =1;
while (counter <= number){
if (counter % 2 !=0){
System.out.println (+ number);
counter++;
}
}
}
My expectation was for it to compare counter to number(the user defined variable) and to keep performing the modulus operation and printing the result, until counter exceeds number. However when I enter a number it just prints that number and keeps grinding away.
Agreed with #forpas, your counter++ is only called once.
Try this...
public static void printOddNumber(int number){
int counter = 1;
while (counter <= number) {
if (counter % 2 !=0) {
System.out.println(counter);
}
counter++;
}
}
A somewhat better answer from a readability standpoint...
public static void printOddNumber(int number){
int counter = 1;
while (counter <= number) {
if (isOddNumber(counter)) {
System.out.println(counter);
}
counter++;
}
}
public static boolean isOddNumber(int number) {
return number % 2 != 0;
}
Once I removed the counter++ statement outside of the loop, I started receiving the correct number of iterations but all showing the number that I had input. I just had to change my System.out.println to display the correct variable, in this case 'counter' not 'number' like I had. My method ended up looking like the first example hooknc put up. Thanks to everyone for all the help.
Related
How to exit from a method, i.e how can i return from a function in this recursion in java?
public class solution {
public static int countZerosRec(int input){
int n=0;
int k =0;
int count=0;
//Base case
if(n==0)
{
return; // How can i return the method from here, i.e how can i stop the execution of the recursive program now.
}
k=input%10;
count++;
n=input/10;
countZerosRec(n);
int myans=count;
return myans;
}
}
Please help me getting out of this method.
This is a program to count number of zeroes.
Example, 34029030 ans = 3
You can try below approach:
public class MyClass {
public static void main(String args[]) {
System.out.println("total zeroes = " + returnZeroesCount(40300));
}
public static int returnZeroesCount(int input){
if(input == 0)
return 0;
int n = input % 10;
return n == 0 ? 1 + returnZeroesCount(input / 10) : returnZeroesCount(input / 10);
}
}
How it works: Assuming your input > 0, we try to get the last digit of the number by taking the modulus by 10. If it is equal to zero, we add one to the value that we will return. And what will be the value that we would be returning? It will be the number of zeroes present in the remaining number after taking out the last digit of input.
For example, in the below case, 40300: we take out 0 in first step, so we return 1+number of zeroes in 4030. Again, it appears as if we have called our recursive function for the input 4030 now. So, we again return 1+number of zeroes in 403.
In next step, since last number is 3, we simply return 0+total number of zeroes in 40 or simply as total number of zeroes present in 40 and so on.
For ending condition, we check if the input is itself 0. If it is zero then this means that we have exhausted the input number and there are no further numbers to check for. Hence, we return zero in that case. Hope this helps.
If your main focus is to find number of zeroes in a given number , You can use this alternatively:
int numOfZeroes =0;
long example = 670880930;
String zeroCounter = String.valueOf(example);
for(int i=0; i< example.length();i++){
if(zeroCounter.charAt(i) ==0){
numOfZeroes++;
}
}
System.out.print("Num of Zeros are"+ numOfZeroes);` `
Instead of posting a code answer to your question, I'll post a few pointers to get you moving.
As #jrahhali said, as your code is, it'll not get past the return
statement inside the if block(which is an error BTW, because you have an int return
type).
I'd recommend that you move the last two lines to some calling
function(such as a main method). That way all this function will
need to do is do some basic processing and move forward.
You aren't checking k at all. As it is, your count is going to
always increment.
Hope this much is enough for you to figure things out.
int count =0;
private int getZeroCount(int num){
if(num+"".length == 1){
if(num==0){
count++;
}
return count;
}
if(num%10 == 0){
count++;
}
num /= 10;
getZeroCount();
}
Method1 :
public static int countZero1(int input) {
int count = 0;
//The loop takes the remainder for the value of the input, and if it is divided by 10, then its number of digits is 0.
// When the value of the input is less than 0, the cycle ends
while (input >0){
if (input % 10 == 0){
count ++;
}
input /= 10;
}
return count;
}
Method2 :
private static int count = 0;
public static int countZero2(int input) {
//Recursive call function
if (input % 10 == 0){
count ++;
}
input /= 10;
if (input <= 0){
return count;
}else {
return countZero2(input);
}
}
public class problem14 {
public static void main(String[] args) {
int biggest = 0;
int biggestNum =0;
for(int i = 1; i<1000001;i++){
if(Solve(i)>biggest){
biggest = Solve(i);
biggestNum = i;
}
}
System.out.println("Chain: " + biggest + "Number: " + biggestNum);
}
public static boolean evenorodd(int num){
//returns true if even, and returns false if odd
int lastNum = num % 10;
if(lastNum==0||lastNum==2||lastNum==4||lastNum==6||lastNum==8){
return true;
}else{
return false;
}
}
public static int Solve(int num){
int count = 1;
int end = 0;
while(end!=1){
if(evenorodd(num)){
num = num/2;
count+=1;
if(num==1){
end=1;
return count;
}
}
if(!evenorodd(num)){
num = 3*num +1;
count+=1;
if(num==1){
end=1;
return count;
}
}
}
return count;
}
}
Sorry guys, I already look up those problem 14 solutions, and I still couldn't figure out why my code doesn't give me the right answer. Please help me, I have trying to figure out for almost a hour now. I just need to know why I am not getting the right answer, since I have been testing out a lot of numbers.
The problem with your algorithm is that in your Solve() method,you are checking if(evenorodd(num)) and if(!evenorodd(num)) separately! Because of this even in case,if your num is even and is processed to yield true result but num becomes 1 at last,and hence it is also getting processed by if(!evenorodd(num)) because it has turned 1 // an odd number.
Second,instead of directly returning count from if-else block,you should better use break statement for exiting the loop and finally returning count!
Try reducing it to if(evenorodd(num)){...} else {...}.
Workout for your int Solve(num) method to ease your effort :-
public static int Solve(int num){
int count = 1;
int end = 0;
while(end!=1){
if(evenorodd(num)){
num = num/2;
count+=1;
if(num==1){
end=1;
break;
}
}
else
{
num = 3*num +1;
count+=1;
if(num==1){
end=1;
break;
}
}
}
return count;
}
I hope it helps and you obtain the correct answer! BEST WISHES...
Your algorithm is fine. You're blowing out on the range of an int. Use longs instead.
A Groovy solution for Project Euler 14
I got the above down-voted, so here's some more detail.
Shekhar is right, you shouldn't be retesting the same condition, but it's actually non-material to your algorithm in this case. A cycle can only complete from the first condition, an even number, anyway. The blog post talks about this and other optimisations you can do to speed up the computation.
You need to make "num" a long, even with the revised non-repeated test algorithm or at various points in your cycle it will exceed the range of an int, and this'll then give you a wrong answer.
Also, you shouldn't call Solve() twice in the outer "i" loop either, store the result of the first call in a variable and just assign it if it's greater.
All that said, you don't need all that code. Less code means less stuff that can go wrong. Here's a simple implementation of a Solve() function that does the job.
public static int Solve(long num) {
int count = 1;
while (num > 1) {
num = (num & 1) == 0 ? num / 2 : 3 * num + 1;
count++;
}
return count;
}
(num & 1) masks off all the bits except the last, so it leaves 0 for an even number, and 1 for an odd number. It's just a shorthand way of doing your evenorodd() function.
The =?: syntax (if you've not seen it before - this is a ternery operator) does the test, then what to return if true, then what to return if false. Again, just a shorthand for an if-then-else where you need to do a single value assignment.
Hope this helps.
I would like to have a program that show range in specific range and show "no primes" once only if there is no primes in that range like 24 to 28.
int count=0;
for(prime = lowerLimit ;prime < upperLimit; prime++)
{
count=0;
for(divisor = 2; divisor <prime; divisor++)
{
if(prime % divisor== 0)
count++;
}
if(count==0)
System.out.println(prime);
}
if (count>0)
System.out.println("nope");
I have tried to put
if (count>0)
System.out.println("nope");
outside the loop,however it also prints when the range having primes.
How can i tackle it?
Keep one extra variable like noOfPrime, which will count the number of prime number with in a range. And increase by 1 if you found any prime, so that out side of loop you could determine the number prime number as well there is any prime number or not.
int count = 0;
int noOfPrime = 0;
...
for(prime = lowerLimit ;prime < upperLimit; prime++){
...
if(count==0){
System.out.println(prime);
noOfPrime+=1;
}
}
if(noOfPrime >0)
System.out.println("no primes);
First of all, your method for detecting primes is terrible. It works, but it's super slow. I'd suggest you look into using sieves if you want to improve that inner loop.
Secondly, what exactly are you trying to count? Right now your count variable stores the amount of divisors a number has, and then you set it to zero when you check the next number. How is that going to tell you anything about how many primes you have in a certain range? You can just do something like this:
notPrime = false;
for(prime = lowerLimit ;prime < upperLimit; prime++)
{
for(divisor = 2; divisor <prime; divisor++)
{
if(prime % divisor== 0){
notPrime = true;
break;
}
if(notPrime)
break;
}
if(notPrime) System.out.println("There's a prime");
You could design a function to determine if a number is prime something like:
//checks whether an int is prime or not.
boolean isPrime(int n) {
//check if n is a multiple of 2
if (n%2==0) return false;
//if not, then just check the odds
for(int i=3;i*i<=n;i+=2) {
if(n%i==0)
return false;
}
return true;
}
and within a for loop, you call the function to each element of the interval:
for(int i=lowerLimit;i<=upperLimit;i++){
if (!(isPrime(i))){
System.out.println("nope");
break;
}
}
Sorry if I have some syntactic errr, I replied from the cell phone.
Everytime you get to the end of the outer loop and count is still 0, it means that you've found a prime number. So if this happens even once, then you're not going to print "nope" at the end. Use a boolean variable to keep track of whether or not you've seen a prime. Since this is homework, I'll let you figure out exactly how to use it. Hint: declare the boolean above both loops.
I am trying to write a while loop like the question indicates that returns the multiples of 7 in decreasing order. At first I was trying to just write a code to return the values before I made then decreasing, but my while loop won't execute. I added a statement printing "Start" just to make sure it was running.
System.out.println("Start");
int number = 7;
int count = 9999;
while (number <= count);
{
System.out.print(number);
number = number + 7;
}
I wrote it this way to be simpler and because I was unsure of how to make number into a string of values and check each one. Any help on this is appreciated. Thank you!
**RESOLVED. Sorry first time on site and I am not sure if there is another way to close this, but thanks to multiple users point out the semi colon and Vikas pointing out the println error, the code runs. As to making it decreasing I just swapped a few things around:
System.out.println("Start");
int number = 9999;
int count = 7;
while (number >= count)
{System.out.println(number);
number = number - 7;
}
}
You have an extra semicolon after the while(). Remove it.
With the semicolon at the end of this line, the while loop has an empty body. The following statements in curly braces are executed after the loop has finished. But the loop will never finish, because the condition is always true, because number never changes.
while (number <= count);
Change it to:
while (number <= count)
{
...
}
You are not able to see the output value for number because it is println and not print
System.out.print(number);
Change this to
System.out.println(number);
And also as others have answered, remove the semi colon ; at the end of while loop.
Having said this, since you want the result to be printed from Descending to Ascending use below code,
System.out.println("Start");
int number = 7;
int count = 9996;
while (number <= count)
{
System.out.println(count);
count = count - number;
}
You have a semicolon at the end of your while loop:
while (number <= count);
which will make it an empty loop. And the following curly braces will only act as a code block and not loop
int count = 9999;
while (count >= 1) {
if (count % 7 == 0) {
System.out.println(count);
}
count--;
}
I used this code and it also worked
System.out.println("Start");
int number = 9999;
int count = 7;
while (number >= count){
if(number%7==0)
System.out.println(number);
number--;
}}}
I have the below program where I am trying to find the sum of first 1000 prime numbers. In the code, what's the difference between solution 1, and 2? Why should I not put the count variable outside the if condition? I am obviously not getting the answer I need if I put the variable outside if, but I don't understand why its logically wrong. It could be a simple thing, but I am unable to figure it out. Experts, please help.
Solution 1:
public class SumOfPrimeNumbers {
public static void main(String[] args) {
long result = 0;
int number = 2;
int count = 0;
while (count < 1000) {
if (checkPrime(number) == true) {
result = result + number;
count++;
}
number++;
}
System.out.println("The sum of first 1000 prime numbers is " + result);
}
public static boolean checkPrime(int number) {
for (int i = 2; i < number; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
Solution 2:
public class SumOfPrimeNumbers {
public static void main(String[] args) {
long result = 0;
int number = 2;
int count = 0;
while (count < 1000) {
if(checkPrime(number)==true)
{
result = result + number;
}
count++; //The count variable here has been moved to outside the loop.
number++;
}
System.out.println("The sum of first 1000 prime numbers is "+ result);
}
public static boolean checkPrime(int number) {
for (int i = 2; i < number; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
You should not check the return value of bool functions for equality to true: this line
if(checkPrime(number)==true)
is equivalent to
if(checkPrime(number))
Finally, the solution where the count is incremented outside of if counts non-primes together with primes, producing an obviously wrong result.
Here are a couple of points "for style" that you should consider:
Checking candidate divisors in checkPrime can stop when the candidate divisor is greater than the square root of the number
You can do much better if you store the primes that you've seen so far, and checking divisibility only by the numbers from the list of primes. When you are looking for the first 1000 primes this would hardly matter, but for larger numbers this could be significant.
The place where you increment count is pretty important. Your first code chunk adds up the first 1000 primes, while the second one adds up all the primes less than 1000.
In your solution 2, count is incremented EVERY time through the loop, regardless of the result of your prime test. So it is not counting primes, but counting iterations through the loop. As a result, you'll check 1,000 consecutive numbers, not consecutive primes (which involves going through a lot more than 1,000 numbers to accumulate).
In addition to what others have pointed out, your check for prime can be made a little more efficient by:
public static boolean checkPrime(int number) {
int s = Math.ceil(Math.sqrt(number));
for (int i = 2; i <= s; i++) {
if ((number % i) == 0) {
return false;
}
}
return true;
}