I have been assigned to write a java program for class that counts multiples. The program takes three integers as input: low, high, x. The program then outputs the number of multiples of x between low and high exclusively.
If the input is: 1, 10, 2
the output would be: 5
My teacher has the proclivity to assign problems we haven't covered in class and I am unsure where to begin. Im not asking for the full code, just how to set up the problem
I am unsure of how to follow my logic thru the program: what I have so far is this
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int low, high, x;
int count = 0;
low = scnr.nextInt();
high = scnr.nextInt();
x = scnr.nextInt();
for(int i = low; i <= high; i++){
if(i % x == 0){
count++;
}
if (i % x != 0){
//System.out.println(count);// someone suggested to move this
}
}
System.out.println(count);
}
}
~~~~~~
If I input 1, 10, 2
My output is 01234
Moved the print of count outside of the loop... man I am tired.
FINAL EDIT: This code works, it accomplishes the goal. Thank you to #charisma and everyone else that helped me understand what was going on here. I am new to java but determined to learn more! Thanks all!!!!!
You can input numbers using scanner class similar to the following code from w3schools:
import java.util.Scanner; // Import the Scanner class
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username");
String userName = myObj.nextLine(); // Read user input
System.out.println("Username is: " + userName); // Output user input
}
}
low, high and x can be of data type int.
To check which numbers between low and high are multiples of x, you can use a for loop. You can declare a new variable count that can be incremented using count++ every time the for loop finds a multiple. The % operator could be useful to find multiples.
You can output using System.out.println(" " + );
Edit:
% operator requires 2 operands and gives the remainder. So if i % x == 0, it means i is a multiple of x, and we do count++.
The value of i will run through low to high.
for (i = low; i <= high; i++) {
if (i % x == 0) {
count++;
}
}
Once you get to the basic implementation (as explained by Charisma), you'll notice, that it can take a lot of time if the numbers are huge: you have high - low + 1 iterations of the loop. Therefore you can start optimizing, to get a result in constant time:
the first multiple is qLow * x, where qLow is the ceiling of the rational quotient ((double) low) / x,
the last multiple is qHigh * x, where qHigh is the floor of the rational quotient ((double) high) / x,
Java provides a Math.floor() and Math.ceil(), but you can get the same result using integer division and playing with the signs:
final int qLow = -(-low / x);
final int qHigh = high / x;
Now you just have to count the number of integers between qLow and qHigh inclusive.
return qHigh - qLow + 1;
Attention: if x < 0, then you need to use qLow - qHigh, so it is safer to use:
return x > 0 ? qHigh - qLow + 1 : qLow - qHigh + 1;
The case x == 0 should be dealt with at the beginning.
put count++; after the last print statement
Related
I'm trying to figure out how to answer this question for my Java class, using only while loops:
Write an application that computes the value of mathematical constant e^x by using the following formula. Allow the user to enter the number of terms to calculate. e^x = 1 + (x/1!) + (x^2/2!) + (x^3/3!) + ...
I can't figure out how I would do this without also asking the user for a value for x? Below is the code that I created for calculating x with the number of terms and just the number 1 for the exponent of each fraction. Any help is appreciated
import java.util.Scanner;
public class FactorialB {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int counter = 0;
float answer = 0;
System.out.print("Enter number of terms: ");
int n = scanner.nextInt();
while (counter < n) {
double factorial = 1;
int factCounter = counter;
while (factCounter > 1) {
factorial = factCounter * factorial;
factCounter--;
}
answer += 1 / factorial;
counter++;
}
System.out.printf("e = %f%n", answer);
}
}
Firstly the question you seem to be asking:
There is no way to make a program that will give e for a specific number unless you ask the user for that number.
However it might be that they just want you to make a method that provides the solution (if it were called) independently of user input. (because the code to get user input isn't very interesting, what is interesting is how you reach the result).
An alternative way to provide x and n are for instance passing them as commandline arguments. (args[] in your main would be a way to provide them)
I would create a separate method that receives x and n that covers the main calculation:
e^x = 1 + (x/1!) + (x^2/2!) + (x^3/3!) + ...
And separate methods that cover 'calculating a single term (x^1/1!), (x^2/2!), etc' and 'factorialize(n)'
public void calculatePartialE_term(int x, int n) {
if (n == 0) {
return 1; // this will allow you to use a while loop, covers the n = 0 case
} else {
// removed the implementation, but basically do
// x^n/n! here for whatever value of n this term is calculating.
}
}
public int calcualteNFactorial(int n) {
// assert n >= 1
// use a while loop to calculate n factorial
}
the benefit of doing this in a separate methods is that you can prove / verify the working of calculatePartialE_term or calcualteNFactorial independently of one another.
now you can simply write a while loop based on x and n to do something like
public int calculateE_to_x(int x, int n) {
int current = 0;
int sum = 0;
while (current <= n) {
sum += calculatePartialE_term(x, current);
}
}
I wouldn't expect your teacher to expect you to show code that handles user input but even if that is the case it will be easier for them to verify your work if the actual work (of calculating) is done in a separate method.
Hi very first Java class and it seems to be going a mile a minute. We learn the basics on a topic and we are asked to produce code for more advanced programs than what helped us get introduced to the topic.
Write a recursive program which takes an integer number as Input. The program takes each digit in the number and add them all together, repeating with the new sum until the result is a single digit.
Your Output should look like exactly this :
################### output example 1
Enter a number : 96374
I am calculating.....
Step 1 : 9 + 6 + 3 + 7 + 4 = 29
Step 2 : 2 + 9 = 11
Step 3 : 1 + 1 =2
Finally Single digit in 3 steps !!!!!
Your answer is 2.
I understand the math java uses to produce the output I want. I can do that much after learning the basics on recursion. But with just setting up the layout and format of the code I am lost. I get errors that make sense but have trouble correcting with my inexperience.
package numout;
import java.util.Scanner;
public class NumOut {
public static void main(String[] args) {
System.out.print("Enter number: ");
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
System.out.println(n);
}
public int sumDigit(int n){
int sum = n % 9;
if(sum == 0){
if(n > 0)
return 9;
}
return sum;
}
}
The output understandably duplicates the code given by the input from the user.
I had trouble calling the second class when I tried to split it up into two. I also know I am not soprln n, or the sum. So I try to make it into one and I can visibly see the problem but am unaware how to find the solution.
Think of recursion as solving a problem by breaking it into similar problems which are smaller. You also need to have a case where the problem is so small that the solution is obvious, or at least easily computed. For example, with your exercise to sum the digits of a number, you need to add the ones digit to the sum of all the other digits. Notice that sum of all the other digits describes a smaller version of the same problem. In this case, the smallest problem will be one with only a single digit.
What this all means, is that you need to write a method sumDigits(int num) that takes the ones digit of num and adds it to the sum of the other digits by recursively calling sumDigits() with a smaller number.
This is how you need to do : basically you are not using any recursion in your code. Recursion is basically function calling itself. Don't be daunted by the language, you will going to enjoy problem solving once you start doing it regularly.
public static void main(String []args){
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
printSingleDightSum(n);
}
public static void printSingleDightSum(int N) {
int sum = 0;
int num = N;
while(num !=0 ){
int a = num%10;
sum + = a;
num = num/10;
}
if(sum < 10) {
System.out.println('single digit sum is '+sum);
return;
} else {
printSingleDightSum(sum);
}
}
Here is the code, I will add comments and an explanation later but for now here is the code:
package numout;
import java.util.Scanner;
public class NumOut {
public static void main(String[] args) {
System.out.println("################### output example 1");
System.out.print("Enter number: ");
final int n = new Scanner(System.in).nextInt();
System.out.print("\nI am Calculating.....");
sumSums(n, 1);
}
public static int sumSums(int n, int step) {
System.out.print("\n\nStep " + step + " : ");
final int num = sumDigit(n);
System.out.print("= " + num);
if(num > 9) {
sumSums(num, step+1);
}
return num;
}
public static int sumDigit(int n) {
int modulo = n % 10;
if(n == 0) return 0;
final int num = sumDigit(n / 10);
if(n / 10 != 0)
System.out.print("+ " + modulo + " ");
else
System.out.print(modulo + " ");
return modulo + num;
}
}
i'm having some trouble recursively adding integers in java from 1^2 to n^2.
I want to be able to recursively do this in the recurvMath method but all i'm getting is an infinite loop.
import java.util.Scanner;
public class Lab9Math {
int count = 0;
static double squareSum = 0;
public static void main(String[] args){
int n = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the value you want n to be: ");
n = scan.nextInt();
Lab9Math est = new Lab9Math();
squareSum = est.recurvMath(n);
System.out.println("Sum is: "+squareSum);
}
public int recurvMath(int n){
System.out.println("N:" +n);
if(n == 0){
return 0;
}//end if
if (n == 1){
return 1;
}//end if
if (n > 1){
return (recurvMath((int) ((int) n+Math.pow(n, 2))));
}//end if
return 0;
}//end method
}//end class
I'm not fully grasping the nature of defining this recursively, as i know that i can get to here:
return (int) (Math.pow(n, 2));
but i can't incorporate the calling of the recurvMath method correctly in order for it to work.
Any help would be appreciated. Thanks!
In general, when trying to solve recursive problems, it helps to try to work them out in your head before programming them.
You want to sum all integers from 12 to n2. The first thing we need to do is express this in a way that lends itself to recursion. Well, another way of stating this sum is:
The sum of all integers from 12 to (n-1)2, plus n2
That first step is usually the hardest because it's the most "obvious". For example, we know that "a + b + c" is the same as "a + b", plus "c", but we have to take a leap of faith of sorts and state it that way to get it into a recursive form.
So, now we have to take care of the special base case, 0:
When n is 0, the sum is 0.
So let's let recurvMath(n) be the sum of all integers from 12 to n2. Then, the above directly translates to:
recurvMath(n) = recurvMath(n-1) + n2
recurvMath(0) = 0
And this is pretty easy to implement:
public int recurvMath(int n){
System.out.println("N:" +n);
if(n == 0){
return 0;
} else {
return recurvMath(n-1) + (n * n);
}
}
Note I've chosen to go with n * n instead of Math.pow(). This is because Math.pow() operates on double, not on int.
By the way, you may also want to protect yourself against a user entering negative numbers as input, which could get you stuck. You could use if (n <= 0) instead of if (n == 0), or check for a negative input and throw e.g. IllegalArgumentException, or even use Math.abs() appropriately and give it the ability to work with negative numbers.
Also, for completeness, let's take a look at the problem in your original code. Your problem line is:
recurvMath((int) ((int) n+Math.pow(n, 2)))
Let's trace through this in our head. One of your int casts is unnecessary but ignoring that, when n == 3 this is recurvMath(3 + Math.pow(3, 2)) which is recurvMath(12). Your number gets larger each time. You never hit your base cases of 1 or 0, and so you never terminate. Eventually you either get an integer overflow with incorrect results, or a stack overflow.
instead of saying:
return (recurvMath((int) ((int) n+Math.pow(n, 2))));
i instead said:
return (int) ((Math.pow(n, 2)+recurvMath(n-1)));
Try this
import java.util.Scanner;
public class Lab9Math {
int count = 0;
static double squareSum = 0;
public static void main(String[] args){
int n = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the value you want n to be: ");
n = scan.nextInt();
Lab9Math est = new Lab9Math();
squareSum = est.recurvMath(n);
System.out.println("Sum is: "+squareSum);
}
public int recurvMath(int n){
System.out.println("N:" +n);
if(n == 1){
return 1;
}//end if
// More simplified solution
return recurvMath(n-1) + (int) Math.pow(n, 2); // Here is made changes
}//end method
}//end class
Here's how it's written in the book:
"The value e^x can be approximated by the following sum:
1+x+x^2/2!+x^3/3!+...+x^n/n!
Write a program that takes a value x as input and outputs this sum for n taken to be each of the values 1 to 10, 50, and 100. Your program should repeat the calculation for new values of x until the user says she or he is through. The expression n! is called the factorial of n and is defined as
n! = 1*2*3*...*n
Use variables of type double to store the factorials (or arrange your calculation to avoid any direct calculation of factorials); otherwise, you are likely to produce integer overflow, that is, integers larger than Java allows."
I don't have any coding problems (not yet at least), my problem is I don't know what it's asking me to do. I get the factorial part (ex. 3i = 1*2*3) but I am just not sure what else it is asking. I have the user input a value for "x" but where does the "n" come from?
"The value e^x can be approximated by the following sum:
1+x+x^2/2!+x^3/3!+...+x^n/n!
" I don't know what this is saying or asking for.
I put together this for loop for the 1-10, 50, 100 part and I don't know if that even makes sense without understanding the rest, but here it is:
for (counter = 1 ; counter <= 100 ;counter++)
{
//System.out.print("Enter value for x: ");
//x = keyIn.nextDouble();
if (counter >= 1 && counter <= 10)
{
if (counter == 1)
System.out.println("Iterations 1-10: ");
System.out.println("test to see if 10 show up");
}
else if (counter == 50)
{
System.out.println("Iteration 50: ");
}
else if (counter == 100)
{
System.out.println("Iteration 100: ");
}
}
I haven't been in algebra in about two years so some of this stuff is throwing me off a bit. Please help with whatever you can, thanks.
It's saying that e^x can be approximated through a Taylor Series: Sum(i:0:n)(xi/fact(i))
So, we have:
double ex_taylor_series(double x, int n)
{
double value;
for(int i = 0; i < n; i++)
{
value += Math.pow(x, i)/(factorial(i));
}
return value;
}
private int factorial (int num)
{
int value = 1;
for(int i = num; i > 1; i--)
{
value *= i;
}
return value;
}
In your case, you would simply feed different values of n, 10, 50 and 100, to ex_taylor_series.
I just gave a coding interview on codility
I was asked the to implement the following, but i was not able to finish it in 20 minutes, now I am here to get ideas form this community
Write a function public int whole_cubes_count ( int A,int B ) where it should return whole cubes within the range
For example if A=8 and B=65, all the possible cubes in the range are 2^3 =8 , 3^3 =27 and 4^3=64, so the function should return count 3
I was not able to figure out how to identify a number as whole cube. How do I solve this problem?
A and B can have range from [-20000 to 20000]
This is what I tried
import java.util.Scanner;
class Solution1 {
public int whole_cubes_count ( int A,int B ) {
int count =0;
while(A<=B)
{
double v = Math.pow(A, 1 / 3); // << What goes here?
System.out.println(v);
if (v<=B)
{
count=count+1;
}
A =A +1;
}
return count ;
}
public static void main(String[] args)
{
System.out.println("Enter 1st Number");
Scanner scan = new Scanner(System.in);
int s1 = scan.nextInt();
System.out.println("Enter 2nd Number");
//Scanner scan = new Scanner(System.in);
int s2 = scan.nextInt();
Solution1 n = new Solution1();
System.out.println(n.whole_cubes_count (s1,s2));
}
}
Down and dirty, that's what I say.
If you only have 20 minutes, then they shouldn't expect super-optimized code. So don't even try. Play to the constraints of the system which say only +20,000 to -20,000 as the range. You know the cube values have to be within 27, since 27 * 27 * 27 = 19683.
public int whole_cubes_count(int a, int b) {
int count = 0;
int cube;
for (int x = -27; x <= 27; x++) {
cube = x * x * x;
if ((cube >= a) && (cube <= b))
count++;
}
return count;
}
For the positive cubes:
i = 1
while i^3 < max
++i
Similarly for the negative cubes but with an absolute value in the comparison.
To make this more general, you need to find the value of i where i^3 >= min, in the case that both min and max are positive. A similar solution works if both min and max are negative.
Well, it can be computed with O(1) complexity, we will need to find the largest cube that fits into the range, and the smallest one. All those that are between will obviously also be inside.
def n_cubes(A, B):
a_cr = int(math.ceil(cube_root(A)))
b_cr = int(math.floor(cube_root(B)))
if b_cr >= a_cr:
return b_cr - a_cr + 1
return 0
just make sure your cube_root returns integers for actual cubes. Complete solution as gist https://gist.github.com/tymofij/9035744
int countNoOfCubes(int a, int b) {
int count = 0;
for (int startsCube = (int) Math.ceil(Math.cbrt(a)); Math.pow(
startsCube, 3.0) <= b; startsCube++) {
count++;
}
return count;
}
The solution suggested by #Tim is faster than the one provided by #Erick, especially when A...B range increased.
Let me quote the ground from github here:
"one can notice that x³ > y³ for any x > y. (that is called monotonic function)
therefore for any x that lies in ∛A ≤ x ≤ ∛B, cube would fit: A ≤ x³ ≤ B
So to get number of cubes which lie within A..B, you can simply count number of integers between ∛A and ∛B. And number of integers between two numbers is their difference."
It seems perfectly correct, isn't it? It works for any power, not only for cube.
Here is my port of cube_root method for java:
/*
* make sure your cube_root returns integers for actual cubes
*/
static double cubeRoot(int x) {
//negative number cannot be raised to a fractional power
double res = Math.copySign(Math.pow(Math.abs(x), (1.0d/3)) , x);
long rounded_res = symmetricRound(res);
if (rounded_res * rounded_res * rounded_res == x)
return rounded_res;
else
return res;
}
private static long symmetricRound( double d ) {
return d < 0 ? - Math.round( -d ) : Math.round( d );
}
I am aware of Math.cbrt in java but with Math.pow approach it is easy to generalize the solution for other exponents.