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;
}
Related
I wrote code that solves polynomials in two ways:
normal form a0x+a1x...an*x
Horner method.
Now, what I need, is to count the amount of multiplications in both classes and compare them. So, my program could decide in which case the Horner method is a better way to solve a polynomial. I couldn't find any ways to count the multiplicators myself.
static int count_2=0;
static int count_1=0;
//---------------------------------------------------------------------------//
public static double evalSimple(double[] a, double x) {
double y_temp = 0;
double y=0;
int n=1;
for(int i=1; i < a.length ; ++i) {
y_temp = (a[i] * Math.pow(x,n));
y = y + y_temp;
++n;
++count_1;
}
System.out.println(count_1);
return y+a[0];
}
//here would be the class to compare the amount of the multiplikations
I tried to initiate the variables count_1 & count_2 and put them in the for-loop, but I didn't get how to return the value (not just to print them in console) of them for the test environment.
A function can always return only one value. But you can make this a result object. I made the example with only one of your methods:
class Result {
double solution;
int iterations;
}
public static Result evalHorner(double[] a, double x) {
Result result = new Result();
for (int i = a.length - 1; i >= 0; i--) {
result.solution = a[i] + result.solution * x;
++result.iterations;
}
return result;
}
Also note that I did not use a global counter variable, so the returned value is fresh for the exact invocation.
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;
}
I am trying to figure out how to count all numbers between two ints(a and b), where all of the digits are divisible with another int(k) and 0 counts as divisible.Here is what I've made so far, but it is looping forever.
for (int i = a; i<=b; i++){
while (i < 10) {
digit = i % 10;
if(digit % k == 0 || digit == 0){
count ++;
}
i = i / 10;
}
}
Also I was thinking about comparing if all of the digits were divisible by counting them and comparing with number of digits int length = (int)Math.Log10(Math.Abs(number)) + 1;
Any help would be appreciated. Thank you!
Once you get in to your while block you're never going to get out of it. The while condition is when i less than 10. You're dividing i by 10 at the end of the whole block. i will never have a chance of getting above 10.
Try this one
public class Calculator {
public static void main(String[] args) {
int a = 2;
int b = 150;
int k = 3;
int count = 0;
for (int i = a; i <= b; i++) {
boolean isDivisible = true;
int num = i;
while (num != 0) {
int digit = num % 10;
if (digit % k != 0) {
isDivisible = false;
break;
}
num /= 10;
}
if (isDivisible) {
count++;
System.out.println(i+" is one such number.");
}
}
System.out.println("Total " + count + " numbers are divisible by " + k);
}
}
Ok, so there are quite a few things going on here, so we'll take this a piece at a time.
for (int i = a; i <= b; i++){
// This line is part of the biggest problem. This will cause the
// loop to skip entirely when you start with a >= 10. I'm assuming
// this is not the case, as you are seeing an infinite loop - which
// will happen when a < 10, for reasons I'll show below.
while (i < 10) {
digit = i % 10;
if(digit % k == 0 || digit == 0){
count ++;
// A missing line here will cause you to get incorrect
// results. You don't terminate the loop, so what you are
// actually counting is every digit that is divisible by k
// in every number between a and b.
}
// This is the other part of the biggest problem. This line
// causes the infinite loop because you are modifying the
// variable you are using as the loop counter. Mutable state is
// tricky like that.
i = i / 10;
}
}
It's possible to re-write this with minimal changes, but there are some improvements you can make that will provide a more readable result. This code is untested, but does compile, and should get you most of the way there.
// Extracting this out into a function is often a good idea.
private int countOfNumbersWithAllDigitsDivisibleByN(final int modBy, final int start, final int end) {
int count = 0;
// I prefer += to ++, as each statement should do only one thing,
// it's easier to reason about
for (int i = start; i <= end; i += 1) {
// Pulling this into a separate function prevents leaking
// state, which was the bulk of the issue in the original.
// Ternary if adds 1 or 0, depending on the result of the
// method call. When the methods are named sensibly, I find
// this can be more readable than a regular if construct.
count += ifAllDigitsDivisibleByN(modBy, i) ? 1 : 0;
}
return count;
}
private boolean ifAllDigitsDivisibleByN(final int modBy, final int i) {
// For smaller numbers, this won't make much of a difference, but
// in principle, there's no real reason to check every instance of
// a particular digit.
for(Integer digit : uniqueDigitsInN(i)) {
if ( !isDigitDivisibleBy(modBy, digit) ) {
return false;
}
}
return true;
}
// The switch to Integer is to avoid Java's auto-boxing, which
// can get expensive inside of a tight loop.
private boolean isDigitDivisibleBy(final Integer modBy, final Integer digit) {
// Always include parens to group sub-expressions, forgetting the
// precedence rules between && and || is a good way to introduce
// bugs.
return digit == 0 || (digit % modBy == 0);
}
private Set<Integer> uniqueDigitsInN(final int number) {
// Sets are an easy and efficient way to cull duplicates.
Set<Integer> digitsInN = new HashSet<>();
for (int n = number; n != 0; n /= 10) {
digitsInN.add(n % 10);
}
return digitsInN;
}
Recently, I've been attempting to create a program that prints prime numbers until a user-specified integer is achieved, the program itself including a "PrimeCheck" class, a "PrimeSieve" class of sorts, and a "Main" class:
public class PrimeCheck {
boolean result;
public PrimeCheck() {
result = true;
}
public boolean primeCheck (int num) {
int i, num1 = num - 1;
for (i = num1; i > 1; i--) {
if (num % i == 0) {
result = false;
}
}
return result;
}
}
import java.util.ArrayList;
public class PrimeSieve {
public PrimeSieve() {
}
PrimeCheck PCObj = new PrimeCheck();
ArrayList<Integer> primes = new ArrayList<Integer>();
public void primeSieve(int num) {
int[] arr = new int[num];
for (int i = 0; i < num; i++) {
arr[i] = i + 1;
if (PCObj.primeCheck(arr[i]) == true) {
primes.add(arr[i]);
}
}
for (int c = 0; c < primes.size(); c++) {
System.out.print(primes.get(c) + " ");
}
}
}
import java.util.Scanner;
public class PrimeSieveMain {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
PrimeSieve PSObj = new PrimeSieve();
System.out.println("Prime Sieve");
System.out.print("Limit: ");
int limit = input.nextInt();
PSObj.primeSieve(limit);
}
}
Pardon my inexperience, yet I cannot seem to locate the problem in this program.
Your problem is in the PrimeCheck class. That class has a state variable (a field) named result. State variables retain the value between calls, for as long as the object is "alive".
So as soon as you hit a number that is not prime, you set this result to false. That value is kept and never changes.
The result variable should be a local variable, not a state variable, and it should be set to true at the beginning of the method. This way it will start fresh every time.
Other notes:
There is really no point in the PrimeCheck class. It doesn't represent a real "entity", and the method can easily be added to the PrimeSieve class. Creating classes for different entities is a good practice, but I think in this case there is no point - it just has one function and that function doesn't depend on anything but its parameters.
If you meant to represent the Sieve of Eratosthenes then this is not the correct algorithm. This is the naive algorithm - it just tests each number individually and doesn't cross out multiples of previous primes as the real Sieve does.
The PrimeCheck has serveral design problems, the first is you designed the result variable as a member, and its only initialized to true upon construction, but updated with false in primeCheck(). Once it has returned false, it will return false on all subsequent calls.
Its also not necessary to design the result as a member, since the result is only related to the method primeCheck(), thus change it to return the value directly, eliminating the member:
public class PrimeCheck {
public boolean primeCheck (int num) {
for (int i = num - 1; i > 1; i--) {
if (num % i == 0) {
return false;
}
}
return true;
}
}
Since PrimeCheck now has no state left, the method could also be made static, making the PrimeCheck instance in your program superflous. You could just call the static method.
PrimeCheck is also terribly inefficient, due to several design choices - one is you start testing from (num - 1), but the most common divisors are the smallest numbers. So it would be more efficient to start testing from the lower end and work the loop upwards. The upper bound (num - 1) is also chosen poorly. The possible largest divisor for num is the square root of num, so the upper bound should be that.
When you get the number is not a prime:
public boolean primeCheck (int num) {
int i, num1 = num - 1;
for (i = num1; i > 1; i--) {
if (num % i == 0) {
result = false;
}
}
return result;
}
result become false, and never change, so I suggest this:
public boolean primeCheck (int num) {
result=true;
int i, num1 = num - 1;
for (i = num1; i > 1; i--) {
if (num % i == 0) {
result = false;
}
}
return result;
}
Before you start to determine prime, you should presume it is a prime
Not tested, just an idea
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