Write a program whose input is two integers, and whose output is the first integer and subsequent increments of 5 as long as the value is less than or equal to the second integer.
-15 10
the output is:
-15 -10 -5 0 5 10
Ex: If the second integer is less than the first as in:
20 5
the output is:
Second integer can't be less than the first. For coding simplicity,
output a space after every integer, including the last.
Here is the code I have gotten so far, however, it is producing an error at the bottom I have an example of the input, my output and what was expected. If anyone has any pointers or can show me updated code it would be appreciated.
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int first = in.nextInt(), second = in.nextInt();
if (first > second) {
System.out.println("Second integer can't be less than the first.");
} else {
while (first <= second) {
System.out.print(first + " ");
first += 10;
}
System.out.println();
}
}
}
Here's what kind of error it is showing:
Input
-15 10
Your output
-15 -5 5
Expected output
-15 -10 -5 0 5 10
You can use the range function from IntStream:
IntStream.range(-15, 10).filter(x -> x % 5 == 0);
As suggested by MC Emperor, there also is a faster solution:
IntStream.iterate(-15, i -> i + 5).limit((10+15)/5);
/**
* The algorithm is as follows:
* iterate(start, i -> i + step).limit((stop-start)/step)
*/
Related
I am writing a code of program that reverse my input, the code that I had written is look like this:
/*
* Author: Mohammed Khalid Alnahdi
*
* This program is reverse the number.
* for example 123 to 321
*
*/
// call utility to take number from the users.
import java.util.Scanner;
class ReverseNumberInput{
public static void main(String[] args){
//we call the tool of take number.
Scanner take = new Scanner(System.in);
int inputNumberUser, printValue = 0;
System.out.print("Please enter the number : ");
inputNumberUser = take.nextInt();
System.out.print("the reverse number is : ");
while(inputNumberUser != 0){
printValue = inputNumberUser % 10;
inputNumberUser = inputNumberUser- printValue;
System.out.printf("%d",printValue);
}
}
}
The answer comes for solve this problem by two why
first solution is replace
inputNumberUser = inputNumberUser- printValue;
by
inputNumberUser = inputNumberUser/10;
and second one is by
while(inputNumberUser != 0){
int digit = inputNumberUser % 10;
printValue = printValue * 10 + digit;
inputNumberUser = inputNumberUser/10;
}
System.out.print(printValue);
My Question why my code in the first not give inputNumberUser zero value while deducting remaining till put the value is zero.
You need to divide the resul of subtraction
inputNumberUser = inputNumberUser- printValue; by 10 after each iteration
For example, you have an input 154
154 - 4 = 150 is your next inputNumberUser
and in the next iteration you have
150 - 0 = 150 is your next inputNumberUser
So your output will be 40000...
If you divide inputNumberUser by 10 after each iteration, you will have
15 - 5 = 10 is your next inputNumberUser
then,
1 - 1 = 0 is your next inputNumberUser
I was trying a programming problem, the statement is
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Like this we have to find the sum of multiples for 't' test cases with 'n' value each, I have tried to find the solution and my code is
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
long t,n,sum;
Scanner in=new Scanner(System.in);
t=in.nextLong();
for(int i=0;i<t;i++)
{
sum=0;
n=in.nextLong();
long l3=0,l5=0,l15=0;
for(int j=3;j>0;j--)
if((n-j)%3==0&&j<n)
{
l3=n-j;
break;
}
for(int j=5;j>0;j--)
if((n-j)%5==0&&j<n)
{
l5=n-j;
break;
}
for(int j=15;j>0;j--)
if((n-j)%15==0&&j<n)
{
l15=n-j;
break;
}
sum+=(float)(((float)l3/(float)3)/(float)2)*(float)(l3+3);
sum+=(float)(((float)l5/(float)5)/(float)2)*(float)(l5+5);
sum-=(float)(((float)l15/(float)15)/(float)2)*(float)(l15+15);
System.out.println(sum);
}
}
}
And the input I gave was,
12
10
11
12
13
1000
1001
1002
1003
100000000
100000001
100000002
100000003
Here 12 is the number of test cases.
And the output I got was
23
33
33
45
233168
234168
234168
235170
2333333593784320
2333333593784320
2333333593784320
2333333593784320
The problem here is the answer is correct for values in the test case 10,11,12,13,1000,1001,1002,1003 but the output is wrong for remaining bigger inputs. I cant find what i am missing. Could you please help me on why I am getting this kind of wrong result and how to rectify it.
You can get a higher precision and a larger numbers by using BigDecimal and BigInteger:
package test;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
long t,n;
BigInteger sum;
Scanner in=new Scanner(System.in);
t=in.nextLong();
for(int i=0;i<t;i++)
{
sum = BigInteger.ZERO;
n=in.nextLong();
long l3=0,l5=0,l15=0;
for(int j=3;j>0;j--)
if((n-j)%3==0&&j<n)
{
l3=n-j;
break;
}
for(int j=5;j>0;j--)
if((n-j)%5==0&&j<n)
{
l5=n-j;
break;
}
for(int j=15;j>0;j--)
if((n-j)%15==0&&j<n)
{
l15=n-j;
break;
}
BigDecimal x = BigDecimal.valueOf(l3)
.divide(BigDecimal.valueOf(6))
.multiply(BigDecimal.valueOf(l3+3));
sum=sum.add(x.toBigIntegerExact());
x = BigDecimal.valueOf(l5)
.divide(BigDecimal.valueOf(10))
.multiply(BigDecimal.valueOf(l5+5));
sum=sum.add(x.toBigIntegerExact());
x = BigDecimal.valueOf(l15)
.divide(BigDecimal.valueOf(30))
.multiply(BigDecimal.valueOf(l15+15));
sum=sum.subtract(x.toBigIntegerExact());
System.out.println(sum);
}
}
}
Without deeper analysis of your code I would guess the problem is that you are using float, which has a quite short value range. Could you try double instead? Not sure what the correct answer would be, but at least you get different results (I just tried)
The solution looks too complex for such a task. I don't understand why do you need to perform the divisions at the end. You can try the following code:
int t = <some number> // the upper bound
int[] dividers = [...] // those are divisors against which we have to test
long sum = 0;
// check all the number up the bound
for (int number = 1; number < t; number++) {
for (int i = 0; i < dividers.length; i++) {
if (number % dividers[i] == 0) {
// the number is divisible without remainder -> add it to the sum
sum += number;
break;
}
}
}
The idea is to iterate all the numbers you want to check and see if they are divisible by some of the N dividers. If you find a number, you add it to the sum and continue with the next one.
Edit:
After the clarifications from OP, I came up with another way to do this.
int t = <some number> // the upper bound
int dividers = [3, 5];
int dividerProduct = dividers[0] * dividers[1];
long sum = calculateSumForDivider(dividers[0], t) + calculateSumForDivider(dividers[1], t) - calculateSumForDivider(dividerProduct, t);
public static int calculateSumForDivider(int divider, int number) {
int n = number / divider;
return divider * n * (n + 1) / 2;
}
What is the logic behind all this?
By dividing the target number, we can calculate how many times does the divider "fit" in the target. This is also the number of numbers in the interval [1, number] that are divisible by the divider. Let's see an example:
t = 10, divider = 3
10 / 3 = 3, so they are 3 numbers in the interval [1, 10], divisible by 3
the numbers are: 1 * 3, 2 * 3, 3 * 3
if we calculate the sum we get 1 * 3 + 2 * 3 + 3 * 3 = 3 * (1 + 2 + 3) = 18
analogically, for = 10, divider = 5
10 / 5 = 2
1 * 5 + 2 * 5 = 5 * (1 + 2) = 15
As a conclusion, we have the following formula for the sum:
sum = divider * n * (n + 1) / 2
where n is the result of the division.
The gotcha here is that numbers, divisible by both 3 and 5 (in other words divisible by 15) are going to be added twice to the sum. To correct this we use the same formula as above to calculate their sum and subtract it from the resulting some, reaching the result.
This solution will only work well for 2 dividers, since with multiple the number of numbers that will be added multiple times to the sum will grow exponentially. F.e. if we want to divide be 3, 4 or 5, we will need to take care of 12, 15, 20, 60, etc.
This will also not work if the two one of the dividers is a power of the other, like 3 and 9. In that case we only need the numbers, divisible by 3.
I am not sure about your algorithm because the simplest one should be like:
sum=0;
n=100100000;
for(int j=1;j<n;j++)
if(j%3==0 || j%5==0)
{
sum+=j;
}
System.out.println(sum);
System.out.println(n*n);
And to get a better idea on what should be the result, it is always less than n*n.
The output I found was:
2338002249916668
10020010000000000
So, as your results where less than n*n, if you are sure about you algorithm, then they are correct.
import java.util.Scanner;
public class findFive {
public static int count = 0;
public static String result = null;
public static void main(String[] args) {
System.out.println("Enter a nonnegative number");
Scanner input = new Scanner(System.in);
int number = input.nextInt();
countFive(number);
System.out.println(count);
}
public static void countFive(int number) {
if (number < 10) {// the base case
if (number == 5) {
count++;
}
} else { // number has two or more digits
countFive(number / 10);
if (number % 10 == 5) {
count++;
}
}
}
}
To put it simply, I do not understand the flow of the countFive(int number) method. I know that if the user enters 5, then the count will simply be equal to 1. However, my confusion comes from where the method is called again inside the method with 'countFive(number/10)'.
EDIT: I would appreciate if someone went through the flow of the code with a number like 552.
If you want to see how this works you should step through the code in your debugger, it will be much more clear when you see it in action
The method is counting how many times the digit 5 occurs in a number. For example if you pass in the number 515 the following will happen
515 is greater than 10
Call countFive(number/10) which evaluates to countFive(51)
51 is greater than 10
Call countFive(number/10) which evaluates to countFive(5)
5 is less than 10
5 equals 5
Increment count
Step out
number%10 == 5 which evaluates to 1%10 == 5 - False
Step out
number%10 == 5 which evaluates to 5%10 == 5 - True
Increment count
countFive(515)
| 515 greater than 10
| countFive(51)
| | 51 greater than 10
| | countFive(5)
| | | count++
| | 51 mod 10 does not equal 5
| 515 mod 10 equals 5
| count++
In recursion base case is created to avoid infinite calls to the same method. That is defined by you below.
if (number < 10) {// the base case
if (number == 5) {
count++;
}
}
If this condition is satisfied, execution comes out of this method. If this isn't true, else block is executed.
else { // number has two or more digits
countFive(number/10); //This is where it is called again
if (number%10 == 5) {
count++;
}
}
In this you have call to countFive(number/10)
Well, the method counts the occurence of 5 in a number. For example, 5123512356 would return 3.
You simply use recursion to remove the last digit of the number until you have reached the highest digit (5 in the example on the left).
Once you have reached it, it will go into number < 10 and see that it indeed is a 5. Then it will leave the method and continues with 51 (51 % 10 = 1), continues with 512, 5123, 51235 (count++) and so on until it is through with the whole number.
To clarify: number/10 is called to reach the highest digit by removing the last digit of the original number until you cannot divide it by 10 any longer. And then the checks go through backwards.
Let's have a look at an easier example: 5050.
1st call: countFive(5050). 5050 > 10, so we call:
2nd call: countFive(5050/10) = countFive(505). Still greater than 10
3rd call: countFive(50)
4th call: countFive(5): counter++, the number is smaller than 10
now we go backwards through these three calls (the last one is finished)
3rd call: 50 % 10 = 0, counter stays the same
2nd call: 505 % 10 = 5, counter++
1st call: 5050 % 10 = 0, counter stays the same
Afterwards: counter = 2.
Let's take the input you proposed: 552 and follow the method.
At the beginning count is 0.
number count number < 10 number == 5 number % 10 == 5
----------- ------- -------------- -------------- ------------------
552 0 false false false
55 0 false false true
1
5 1 true true true
2
And it'll return 2. Basically as you can see the method counts the number of occurrences of the digit 5 in the input.
Your base case checks if it's a digit (< 10) and if so checks if the digit is 5. Otherwise, it chops the right-most digit and calls the method again, as if the input was that new number. It stops once the number is left with only a single digit.
import java.util.Scanner;
class Factorial {
public static void main(String args[]) {
int n, c, fact = 1;
System.out.println("Enter an integer to calculate it's factorial");
Scanner in = new Scanner(System.in);
n = in.nextInt();
if ( n < 0 )
System.out.println("Number should be non-negative.");
else
{
for ( c = 1 ; c <= n ; c++ )
fact = fact*c;
System.out.println("Factorial of "+n+" is = "+fact);
}
}
}
For this code for finding the factorial of a number, I don't get the part where it says, "fact=fact*c".
I know it's because fact gets "updated" with a new multiplication factor of c, but do the numbers multiply?
Example: n=3 and c=1,2,3 and fact=1.. then would the process look like, (1*1) * (1*2) * (1*3)= 6?
The expression
fact = fact * c;
multiplies fact by c and stores the result in fact.
Thus the following happens when the code is run:
At the start , fact is 1.
On the first iteration it gets multiplied by 1 the result of which is 1.
On the second iteration it gets multiplied by 2 and becomes 2.
On the third iteration it gets multiplied by 3 and becomes 6.
On the fourth iteration it gets multiplied by 4 and becomes 24.
and so on.
You are right it works like this:
fact is 1 initially
loop when c = 1:
multiply c with fact i.e. 1 * 1
store the result back in fact i.e. fact = 1
loop when c = 2
multiply c with fact i.e. 1 * 2
store the result back in fact i.e. fact = 2
loop when c = 3
multiply c with fact i.e. 2 * 3
store the result back in fact i.e. fact = 6
I decided to just try and get the small example of only going to 10 like the example shown.
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 >and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
public class project1 {
public static void main(String[] args) {
int three=0;
int tot3=0;
int five=0;
int tot5=0;
int total;
while (tot3<10) {
three+=3;
tot3=tot3+three;
};
while (tot5<10) {
five+=5;
tot5=tot5+five;
};
total=tot3+tot5;
System.out.println("Three's: " + tot3);
System.out.println("Five's: " + tot5);
System.out.println("Combined: " + total);
}
}
My output is as show:
Three's: 18
Five's: 15
Combined: 33
Numbers that are both multiples of 3 and 5 (like 15 for instance), are counted twice - once in each loop.
while (tot3<10) {
three+=3;
tot3=tot3+three;
};
I think you mean
while (tot3<10) {
three += tot3; // Add this multiple of 3 to the total.
tot3+=3; // increment the "next multiple"
}
(same for 5)
Lone nebula also makes a good point - you'd need to add logic to the "5" loop to check it's not already counted in the 3 loop. The mod (%) operator can help there.
First,
while (tot3<10) {
three+=3;
tot3=tot3+three;
};
while (tot5<10) {
five+=5;
tot5=tot5+five;
};
This should be
while (three<10) {
three+=3;
tot3=tot3+three;
};
while (five<10) {
five+=5;
tot5=tot5+five;
};
Because you're concerned about when you start counting numbers above 10, not when your TOTAL of those numbers is above 10.
Secondly, your solution will count numbers that are a multiple of three and of five twice. For example, 15 will be added twice. Learn about the modulo operator, %, to come up with a solution to this (for example, not adding five to the tot5 count if five % 3 == 0)
I would recommend looking into using the modular operator to solve this problem. In java % will allow you to perform modular arithmetic. For example any multiple of 3 such as 9 % 3 = 0 while 9 % 2 = 1. It can be thought of as what remains after you divide the first number by the second. All multiples of a number modded by that number will return zero.
Keep track of your variables through the loop and you'll see the problem:
for tot3
=3
=9
=18
=30
You're keeping track of the sum, instead of tracking the multiples. This problem is partially solved in by
while(three<10)
Again, keeping track of the variable through the loop you'll see that this is wrong- it stops at 12, not 9 as you want it. Change it to
While(three<9)
//ie the last divisible number before the limit, or that limit if its divisible (in the case of 5)
All said, an infinitely more elegant solution would involve modulus and a nice little if statement. I hope this helps!
public class project1 {
public static void main(String[] args) {
int number = 0;
int total = 0;
while (number < 10) {
System.out.println(number);
if ((number % 3) == 0) {
System.out.println(number + " is a multiple of 3");
total = total + number;
}
else if ((number % 5) == 0) {
System.out.println(number + " is a multiple of 5");
total = total+number;
}
number++;
}
System.out.println("total = "+ total);
}
}
Looking at how slow I was, I did roughly the same thing as everyone else but swapped to a modulus function. The modulus function gives you the remainder(int) of dividing the first number by the second number, and can be compared to another integer. Here I have used it to check if the current number is directly divisible by 3 or 5, and add it to the total if the value is true.
Try this
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for(int a0 = 0; a0 < t; a0++){
long n = in.nextLong()-1;
System.out.println((n-n%3)*(n/3+1)/2 + (n-n%5)*(n/5+1)/2 - (n-n%15)*(n/15+1)/2);
}
}
}