Java method to get sum of int based on test logic - java

I am new to learning java and I have a written a method below. I am trying to understand how to satisfy the tester methods. Is there a way to get the correct logic with the while loop?
I stated that the sum = 0 and while the sum is less than i, increment the sum and loop till it reaches i then return the sum (or thats what i think that's what im trying to do) to satisfy the test. When i look at the junit error message for 1) it says its giving me 10 but expects 55, 2) says im getting 49 but expects 1225. 3) is satisfied. What am i doing wrong here? Is it possible to do this method either with an if statement or while loop?
public int sumOfInts(int i) {
int sum = 0;
while(sum < i)
++sum;
return sum;
}
public void testSumOfInts2() {
int sumOfInts = math.sumOfInts(10);
assertEquals(55, sumOfInts);
public void testSumOfInts3() {
int sumOfInts = math.sumOfInts(49);
assertEquals(1225, sumOfInts);
public void testSumOfInts4() {
int sumOfInts = math.sumOfInts(-49);
assertEquals(0, sumOfInts);

You are looking to make a method that gives you the cumulative sum. The method you have written just gives you the number of times it runs, which is exactly the number you have provided as argument.
You need to differentiate between the counter (the argument) and the cumulative sum, and also update the value of the counter so that the while loop knows when to exit.
Lastly, the <= comparison is necessary to get the correct value (vs just <).
Here is an example:
public int sumOfInts(int i) {
int sum = 0;
int counter = 0;
while(counter <= i) {
sum = sum + counter;
counter = counter + 1;
}
return sum;
}

Try this
public int sumOfInts(int i) {
int sum = 0;
int iteration = 0;
while(iteration < i){
sum = sum+iteration;
iteration++;
}
return sum;
}

Related

Why is code skipping over for loop in integer length program

Im trying to create a program to find the length of a given number. I thought i would do this by taking the number and dividing by 10 and then checking to see if the number was <= 0. I dident want to edit the global number so i created a instance version of the number and used that as the condition in the for loop.
So obviously this dident work so naturally i ended up looking in the debugger to figure out what was going on. It looks as if the program is completely skipping over the for loop any help would be appreciated.
public static void sumFirstAndLastDigit(int number) {
int numberLength = 0;
int instanceNumber = number;
for(int i = 0; instanceNumber <= 0; i++) {
instanceNumber /= 10;
numberLength = i;
}
System.out.println("Number length = " + numberLength);
// to find length of number loop division by 10
}
}
The program should use the for loop to keep dividing by 10 until the number is = to or less than than zero and for how many times the loop ran should be stored in the number length integer. In this case with the number 12321 the answer should be 6 but it prints 0.
You're telling it to loop while instanceNumber <= 0. The "test" in a for loop is a "keep going" test, not a termination test. The loop continues as long as the test is true.
From your description, you want instanceNumber > 0.
Also note Avinash Gupta's point that with your current code, you'll undercount by one. I'd address that by using a completely different loop:
int numberLength = 0;
int instanceNumber = number;
while (instanceNumber > 0) {
++numberLength;
instanceNumber /= 10;
}
That's nice and unambiguous: If instanceNumber > 0, it increments numberLength, then divides by 10 and tries again.
This will print the correct output
public static void sumFirstAndLastDigit(int number) {
int numberLength = 0;
int instanceNumber = number;
for(int i = 0; instanceNumber > 0; i++) {
instanceNumber /= 10;
numberLength = i;
}
System.out.println("Number length = " + (numberLength + 1));
}
Your code will be much more comprehensive if you use while loop for your algorithm.
public static void sumFirstAndLastDigit(int number) {
int numberLength = 0;
int instanceNumber = number;
while(instanceNumber != 0) {
instanceNumber /= 10;
numberLength += 1;
}
System.out.println("Number length = " + numberLength);
// to find length of number loop division by 10
}
Consider even more sophisticated solution:
public static void sumFirstAndLastDigit(int number) {
int numberLength = (int) (Math.log10(number) + 1);
System.out.println("Number length = " + numberLength);
}
Taken from Baeldung

Loop never starting

I am trying to write a small method which will calculate the exponent given a number and power (I know about math.pow I am just doing this for kicks). However the loop inside my method never starts and I cant figure out why. My code is below, all help appreciated.
public static void main(String[] args) {
int result = exponantCalculation(2, 3);
System.out.println(result);
}
public static int exponantCalculation(int number, int power) {
for (int i = 1;i >= power;i++) {
number = number * number;
}
return number;
}
You've used the wrong comparison operator in the loop condition (>=, should be <= or < — see other answers).
Not sure, maybe this was intentional, BUT if the method is meant to calculate "number to the power of power", then you're incorrectly squaring the result of the previous iteration. This will produce a much higher value that the number to the power of power.
You need to introduce a new variable and multiply it with number in the loop, e.g.
long result = 1;
for (int i = 0; i < power; i++) {
result *= number; // same as "result = result * number"
}
return result;
Minor note: I've intentionally used long type for the result, which can slightly defer the integer overflow problem for big values.
Condition inside for loop is wrong.
Since you are passing 3 as power in your method as parameter, i is initialized with 1 and then condition gets checked whether i>=power with is obviously not true in this case so your loop never starts.
Change
for (int i = 1;i >= power;i++)
to
for (int i = 1;i <= power;i++)
if you wish to calculate the power of any number, you can use following method
public static int exponantCalculation(int number, int power) {
int result = 1;
for (int i = 1;i <= power;i++) {
result = result * number;
}
return result;
}
The for loop condition was wrong, but also you need to sotre the result in another variable:
public static int exponantCalculation(int number, int power) {
if(power == 0){
return 1;
}
int result = 1;
for (int i = 1;i <= power;i++) {
result *= number;
}
return result;
}

Trailing Zeroes of a Factorial

I'm trying to solve this coding question:
Given an integer n, return the number of trailing zeroes in n!
Below is my code (codec this up using the wiki link)
public int trailingZeroes(int n) {
int count = 0, i = 5;
while(i<=n){
count+= n/i;
i*=5;
}
return count;
}
This runs for all test cases except when n = Integer.MAX_VALUE upon which I get a TLE. How can I fix this code to make it cover that test case. I have read about five articles on the net and everything seems to agree with my approach.
Much thanks.
So, I followed the long/BigInteger approach (thanks y'all):
public int trailingZeroes(int n) {
long count = 0;
for(long i= 5; n/i >= 1; i= i*5){
count+= n/i;
}
return (int)count;
}
As Iaune observed, your loop will never terminate when n is Integer.MAX_VALUE, because there is no int greater than that number (by definition). You should be able to restructure your loop to avoid that problem. For instance, this is the same basic approach, but flipped upside-down:
public int trailingZeroes(int n) {
int count = 0;
while (n > 0) {
n /= 5;
count += n;
}
return count;
}
You cannot write a for or while loop where the loop counter is an int and the upper limit is <= Integer.MAX_VALUE.
What happens with a simple increment (counter++) is that the loop counter is set to that value, the body executes and then the counter is incremented which results in a negative number, Integer.MIN_VALUE. And then everything happens all over again.
Other weird things may happen when the loop counter is incremented in quantities > 1 or (as here) is multiplied: the int loop counter just can't hold a value > Integer.MAX_VALUE
Consider another approach for iterating over these numbers. Or handle MAX_VALUE separately.
Your problem is that once i gets large enough (more than Integer.MAX_INT / 5) then the line i*=5; causes i to overflow to the "wrong" value. The value in question is 5 to the 14th power, which is 6103515625, but which overflows to 1808548329.
The result of this is that the loop just keeps executing forever. i will never become a value that's not <= Integer.MAX_INT, because there's just no such int.
To avoid this, you need i to be a larger data type than an int. If you change i and count in your original code to long, this will work fine. Of course, BigInteger would also work.
public class FactorialNumberTrailingZeros {
public static void main(String[] args) {
System.out.println(trailingZeroes(1000020));
}
private static int trailingZeroes(int n) {
int count = 0;
while (n > 0 && (n % 10 == 0)) {
n /= 10;
count ++;
}
return count;
}
}
public static void main(String[] args) {
int result = findFactorialTrailingZero(100);
System.out.println("no of trailing zeros are " + result);
}
public static int findFactorialTrailingZero(int no) {
int zeros = no / 5;
int zeroIncrementNo = 25;
int zerosIncrementFactor = 1;
int nextZeroIncrenent = 5;
for (int i = 1;no >= zeroIncrementNo; i++) {
zeros=zeros+zerosIncrementFactor;
zeroIncrementNo=25*(i+1);
if(i+1==nextZeroIncrenent){
zerosIncrementFactor++;
nextZeroIncrenent=nextZeroIncrenent*5;
}
}
return zeros;
/*
[n/5]+[n/25]+[n/125]+....
if n<25 then [n/5]
if n<125 then [n/5]+[n/25]
if n<625 then [n/5]+[n/25]+[n/125]
*/
#include<bits/stdc++.h>
#include<iostream>
using namespace std;
int countTrailingZeroes(int n)
{
int res=0;
for(int i=5;i<=n;i=i*5){
res=res+n/i;
}
return res;
}
int main(){
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int n;
cin>>n;
cout<<countTrailingZeroes(n);
return 0;
}
Output
25
6
Explanation:
25!=1.551121e+25 i.e contains 6 trailing zeroes
Here is my python code that could solve your problem:
def check(n):
j,ans=5,0
while j<=n:
ans=ans+n//j
j=j*5
return ans

writing a method for fibonacci sequence

I'm trying to write a for loop that calls the method fibonacci and prints the first 25 numbers in the fibonacci sequence. The problem is I'm a little confused about how to do that correctly. I'm a little confused about when the for loop in the run method calls the fibonacci method do the values inside the fibonacci method reset after reach pass of the for loop? So for example during the first pass of the for loop i = 0 and the values for int a and int b change inside the the fibonacci method. Do the values inside the fibonacci method reset on the next pass of the for loop?
import acm.program.*;
public class Fibonacci extends ConsoleProgram{
private void run(){
for(int i = 0; i <= 25; i++){
fibonacci(i);
println(fibonacci(i));
}
}
private int fibonacci(int n){
int n = 0;
int a = 0;
int b = 1;
while (n < 25);
int c = a + b;
a = b;
b = c;
}
return(a);
}
You're looping in two different places - run() and fibonacci(). Only one of these places should care about the loop, and the other should care about computing Fibonacci(n).
What we can do remove the loop from fibonacci, and only rely on the loop on the outside. Also, we're going to remove that statement int n = 0, since that shadows the parameter you're passing in.
Lastly, we're going to create two new static variables a and b, so that the values of those are preserved with this instance. If you don't do that, then you'd have to rely on either recursion or some other methodology to provide the appropriate values of a and b.
I'm not entirely sure why you need to extend ConsoleProgram, but I'll leave it in for now.
So, here's what it should look like.
public class Fibonacci extends ConsoleProgram {
static int a = 0;
static int b = 1;
public void run() {
for(int i = 0; i <= 25; i++) {
// Print the call to fibonacci(i) with every iteration.
}
}
private int fibonacci(int n) {
int c = a + b;
a = b;
b = c;
return c;
}
}
Fibonacci it's a typical example of an algorithm that can be easily approached with recursion, that's because:
you can divide the entire fibonacci sequence in steps,
in each step you have to do the same thing except for the final step where you got 0,
and the last step is "special" because 0 times any number gives you 0,
so if you apply the same step as before you simply nullify everything, this means that when your counter is 0 you have to do something different from your previous steps and it's:
multiply the result that you have stored by 1 and not by 0 ( or you can leave it as it is, it's the same thing as multiply by 1
exit the loop and terminate the fibonacci sequence
Internet is full of Fibonacci examples, 1 & 2 are more than enough for you.
The variables reset for each iteration of the loop. The variables a, b, and c are local variables that only "live" within the method. Every call to the fibonacci(n) method should start from the beginning of the fibonacci sequence and print out the terms up until the nth term. Therefore, while (n < 25); should not be part of the method. Also, int n = 0 resets n to zero, which is bad because we need to know what n is to get the nth term.
The ideal way to do this loop is:
private void fibonacci(int n) {
int i = 1; // a new variable i to count from the 1st term
int a = 0; // the first term
int b = 1; // the second term
while (i <= n) {
int c = a + b; // the new value for b
a = b; // switch the old a for the new a
b = c; // get the (i + 1)th term for the next iteration
System.out.println(a); // print out the ith term
i++;
}
}
You are not storing the returned int value of fibonacci();
int currentSum=0;
for(int i = 0; i <= 25; i++){
currentSum+=fibonacci(i);
println(currentSum);
}
and why do you have another variable n in your fibonacci(int n) ?
Please make sure first your fibonacci method is working. (The infinite while loop, etc.)
public static void main (String args[]){
for(int i = 0; i<25; i++) {
System.out.println(fibonacci(i));
}
}
static int fibonacci(int n){
if(n==0) {
return 0;
}
int a = 0;
int b = 1;
for(int i = 0; i < n; i++){
int temp = b;
b += a;
a = temp;
}
return(b);
}

Java Program Calculation

Write a program in Java to calculate the following:
1+2-3+4-5 …-99+100
this program is provably very simple but I am a beginner to java and this is what i have so far I'm not sure if i am in the right path
I get one java: 13 error message error:not a statement sub;
class Loop{
public static void main(String[] args){
int sum=0;
int sum=0;
int sub=0;
while(num<100){
num++;
if(num%2 == 0){
sum=sum+num;
}
sub;
if(num%3== 0||num%5==0||num%7==0){
sub=sub-num;
}
}
System.out.println("Sum is: " +sum+sub);
}
}
This is complaining about this line:
sub;
This is not a valid instruction, which is why the compiler is yelling at you.
In the following:
if(num%2 == 0){
sum=sum+num;
}
sub;
That last line sub; is not a Java statement. You probably want to delete it.
Update:
Looks like you want to add even and subtract odd (except for 1 which you want to add). If I understood the requirement properly:
You can start by declaring two variables as follows:
int sum = 1; //this will add 1
int n = 2;
Loop condition should be as follows:
while(n <= 100) { //because you want to include 100 also
Then on each iteration of the loop:
If n is even add it to sum, else if n is odd subtract it from sum.
After that increment n by 1.
Finally, print the value of sum.
You can using simple way to implement it :
public static void main(String[] args) {
int sum = 1;
for (int i = 2; i < 100; i++) {
if (i % 2 == 0) {
sum = sum + i;
} else {
sum = sum - i;
}
}
System.out.println(sum);
}
class Loop{
public static void main(String[] args){
int sum=0;
int sum=0;
int sub=0;
while(num<100){
num++;
if(num%2 == 0){
sum=sum+num;
}
sub; <-- sub is not a statment
if(num%3== 0||num%5==0||num%7==0){
sub=sub-num;
}
}
System.out.println("Sum is: " +sum+sub);
}
}
You are on the right track, with a little trial and error you will get it :-) The cause of your problem is commented in the code above, in the middle of your program you have a random sub; on its own line. sub doesn't have a meaning in that context so the compiler doesn't know how to treat it.
1) You can't have 2 variables with the same name sum
2) You need to declare and initialize a variable before you use it
3) What does the statement sub; signify?
Make all the chages mentioned above and try!
Well, you declare "sum" twice, and "sub;" isn't a valid expression.
class Loop{
public static void main(String[] args){
int sum=0;
int sum=0; // second declaration? should probably be num, right?
int sub=0;
while(num<100){
num++;
if(num%2 == 0){
sum=sum+num;
}
sub; // what's this doing here?
if(num%3== 0||num%5==0||num%7==0){
sub=sub-num;
}
}
System.out.println("Sum is: " +sum+sub);
}
}
public class Loop {
public static void main(String[] args) {
int sum = 1;
int sub = 0;
for (int i = 2; i <= 100; i += 2)
//sum =sum+i;
sum +=i;
System.out.println(sum);
for (int i = 3; i <= 100; i += 2)
sub += i;
System.out.println(sub);
System.out.println("Sum is: " +(sum-sub));
}
}
Try this code will give you your desired result

Categories

Resources