find divisble for a number from x to y - java

currently im trying to find the divisibility for a number the user inputs and the number should be divisible from x to y
example: 2520 is divisible by all numbers from 1-10.
so here is what i done so far, so clearly i coded it in a bad way, can anyone do better?
public static void main (String[] args){
Scanner kb = new Scanner(System.in);
int temp = 0,x,y,num;
System.out.println("enter the number to check for");
num = kb.nextInt();
System.out.println("enter the starting number");
x = kb.nextInt();
System.out.println("enter the ending number");
y=kb.nextInt();
while(x >= y){
System.out.println("starting num must be less then the ending num,re-enter the starting num.");
x = kb.nextInt();
System.out.println(" now enter the ending number, must be greater then the starting num");
y=kb.nextInt();
}
while ( num % x == 0 && x < y){
x++;
}
if ( x == y){
System.out.println("the number "+ num + " is divisble by this range.");
}
}
}

Write it as a helper method:
public static boolean isDivisibleByAll(int dividend, int fromDivisor, int toDivisor) {
for (int divisor = fromDivisor; divisor <= toDivisor; divisor++)
if (dividend % divisor != 0)
return false;
return true;
}

Some things to consider:
It would be more user-friendly if you accepted the integers in either order. If the first is larger than the second, just go from the second to the first. So, something like:
int swapInt;
if (x > y)
{
swapInt = x;
x = y;
y = swapInt;
}
It would be more user-friendly if you accepted the same integer for the start and end. The user might want to just check one number. (How would you change your code to do this?)
It looks like you accept any integers, including zero and negative integers. Will your program still work? If not, what would you have to change?

Related

How to generate odd numbers based on user input conditions

The application should print the first n odd numbers, where n is between 1 and 25, starting at start. start is between 100 and 200 and it says where the odd number sequence should start. If start is an even number then the sequence should start at the next odd number.
Here is and example with n = 4 and start = 193:
193, 195, 197, 199
The application must allow the user to enter values for n and start. It must then verify that n is between 1 and 25 and start is between 100 and 200.
My code so far:
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
int n = sc.nextInt();
Scanner sc2= new Scanner(System.in);
int start = sc2.nextInt();
for (int i=start; i=n; i=start+1+=2)
if ((n>=1) && (n<=25)) {
System.out.println("Valid Input!");
}
else
System.out.println ("Invalid Input!!!");
if ((start>=100) && (start<=200)){
System.out.println ("Valid Input!");
}
else
System.out.println("Invalid Input!!!");
if (start%2==0) {
System.out.println ("Even Number Inputted! Next Odd Number displayed.");
}
}
It keeps telling me that int cannot be converted to boolean. I understand what it says just not sure how to rectify it.
First, prompt for the values
int minN = 1;
int maxN = 25;
int minStart = 100;
int maxStart = 200;
int start = getInput("Please enter starting value: ", minStart, maxStart);
int n = getInput("Please enter number of odd numbers to print: ", minN, maxN);
Now compute and print the results for start = 190 and n = 4
for (int i = start | 1; i <= maxStart && n-- > 0; i += 2) {
System.out.println(i);
}
prints
191
193
195
197
Explanation
First, the user is prompted for input using a method.
start - the starting point selected by the user
n - the number of values to generate also selected by the user
Then a loop is used to generate the values. This works by first, ensuring the start is odd by setting the low order bit to a 1. If the value is already odd, this has no effect. The loop begins with the first odd from start and increments by 2. The loop terminates if either i exceeds maxStart or n reaches 0.
The prompt method accepts a prompt message that is appropriate for the type of input. It also accepts a range to provide a helpful reprompt if the choice is out of range. As long as the user enters out of range values, the method will keep prompting. Otherwise, it returns the accepted value.
static Scanner input = new Scanner(System.in);
public static int getInput(String prompt, int min, int max) {
int value;
while (true) {
System.out.print(prompt);
if ((value = input.nextInt()) >= min && value <= max) {
break;
}
System.out.printf(
"Invalid entry, must be between %d and %d inclusive", min, max);
}
return value;
}
You only need one Scanner. You should perform input validation before your display loop. And your for loop syntax is incorrect, the second part should resolve to a boolean test (not an assignment) and i=start+1+=2 is just wrong. Fixing it might look something like
Scanner sc = new Scanner(System.in);
int n;
do {
System.out.println("Print how many odd numbers (n)? Enter a value between 1 and 25.");
n = sc.nextInt();
} while (n < 1 || n > 25);
int start;
do {
System.out.println("Enter starting value? Enter a value between 100 and 200.");
start = sc.nextInt();
} while (start < 100 || start > 200);
if (start % 2 != 1) {
System.out.println("Even Number Inputted! Next Odd Number displayed.");
start++;
}
for (int i = start; i < start + (2 * n); i += 2) {
System.out.println(i);
}
The problem is in the for loop condition, you must change i=n into i<=n
This is my first time posting so bare with me.
I believe that the reason you are getting int cannot be converted to boolean is because in your for loop, the second statement says i=n. This statement of the for loop needs to be a logic block.
I am a firm believer in giving resources rather than the answer, so check out this write up done by w3schools (killer resource btw) on for loops in java: https://www.w3schools.com/java/java_for_loop.asp
I believe problem is for loop at the condition part, i cannot be equal n like i=n. You can change it i<=n

How to speed up the efficiency of my code?

Essentially I'm trying to create a program that counts up the sum of the digits of the number, but every time a number that is over 1000 pops up, the digits don't add up correctly. I can't use % or division or multiplication in this program which makes it really hard imo. Requirements are that if the user inputs any integer, n, then I will have to be able to compute the sum of that number.
I've already tried doing x>=1000, x>=10000, and so forth a multitude of times but I realized that there must be some sort of way to do it faster without having to do it manually.
import java.util.Scanner;
public class Bonus {
public static void main(String[] args) {
int x;
int y=0;
int u=0;
Scanner s = new Scanner(System.in);
System.out.print("Enter the number:");
x = s.nextInt();
int sum = 0;
{
while(x >= 100) {
x = x - 100;
y = y + 1;
}
while(x>=10) {
x = x - 10;
u = u + 1;
}
sum = y + u + x;
System.out.println("The sum of the digits in your number is" + " " + sum);
}
}
}
So if I type in 1,000 it displays 10. And if I type in 100,000 it displays 100. Any help is appreciated
Convert the number to a string, then iterate through each character in the string, adding its integer value to your sum.
int sum = 0;
x = s.nextInt();
for(char c : Integer.toString(x).toCharArray()) {
sum += Character.getNumericValue(c);
}

Java application integer

I'm trying to create my fist java application with an if statement that will take an integer (e.x 22) and find out if its sum is equal when multiplied and subtract (e.x 2*2=4 and 2+2=4) or if its not.
Though i can't figure out how to do the if decision. can someone point out how to do that?
thank u
package 1;
import java.util.Scanner;
public class 1
{
public static void main(String[] args)
{
Scanner input = new Scanner( System.in );
int x;
int y;
System.out.print( "Enter a number from 10 to 99: " );
x = input.nextInt();
if ( x >= 10 && x <= 99 )
{
x= x % 10;
x= x / 10;
}
else
{
System.out.println( "you must enter a number from 10 to 99" );
}
}
}
You just need to assign them to different variable and check for the condition
if (x >= 10 && x <= 99) {
int first = x / 10; // Take out the first digit and assign it to a variable first
int second = x % 10; // Take out the second digit and assign it to a variable second
if (first * second == first + second) { // Check for your condition, which you mentioned in your question
System.out.println("Yep, they match the condition"); // If it satisfies the condition
} else {
System.out.println("Nope, they don't match the condition"); // If it doesn't satisfy the condition
}
}
P.S: You question said multiplied and subtract but the example just after the example was (e.x 2 x 2=4 and 2+2=4). I went with the ex.
try
import java.util.Scanner;
public class One {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x;
int y;
System.out.print("Enter a number from 10 to 99: ");
x = input.nextInt();
if (x >= 10 && x <= 99) {
y = x % 10;
x = x/10 ;
if(x* y== x+ y)){
System.out.println("Sum and product are equal" );
}
else
System.out.println("Sum and product are not equal" );
} else {
System.out.println("you must enter a number from 10 to 99");
}
input.close();
}
}

Doing one more iteration after DO-While loops stops?

I am writing a Babylonian algorithm for computing the square root of a positive number, and the iteration should keep going until the guess is within 1% of the previous guess.
the code that I have written gets the iteration going to the one before error is 1%. how can I make it to do one more iteration ?
to get the question straight, is there a way to tell it iterate untill the error is <1% ?
import java.util.Scanner;
public class sqrt {
public static void main(String[] args){
Scanner kb = new Scanner(System.in);
System.out.print("\nplease enter the desired positive number in order to find its root of two: ");
double num = kb.nextDouble();
double guess=0;
double r, g1, error;
if (num>=0){
guess = num/2;
do{
r = num/guess;
g1 = guess;
guess = (guess+r)/2;
error = (guess-g1)/guess;
if (error<0){
error = -error;
}
}
while(error>0.01);
System.out.println("The square root of the number " + num +" is equal to " +guess);
} else {
System.out.println("Sorry the number that you entered is not a positive number, and it does not have a root of two");
}
}
}
Add a new counter that only gets increased in the (former) exit loop condition.
int exit = 0;
do {
...
if (error <= 0.01) {
exit++;
}
} while (exit < 2);
If you want to return a value only when the error is strictly less than 1%, you need to change the while condition.
Changing it to error >= 0.01 says "iterate, even when error is exactly equal to 1%, so we get a final error less than 1%".
Also, your if (num <= 0) allows a division by zero to happen, when num is exactly zero.
Let's check:
num = 0;
guess = num / 2; // guess = 0
r = num / guess; // r = 0 / 0
Looking at the below code should give you a clearer idea. I've commented it.
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.print("\nPlease enter the desired positive number in order to find its root of two: ");
double num = kb.nextDouble();
double guess=0;
double r, g1, error;
// Previous code allowed a division by zero to happen.
// You may return immediately when it's zero.
// Besides, you ask clearly for a *positive* number.
// You should check firstly if the input is invalid.
if (num < 0) {
System.out.println("Sorry the number that you entered is not a positive number, and it does not have a root of two");
}
// Since you assigned guess to zero, which is the sqrt of zero,
// you only have to guess when it's strictly positive.
if (num > 0) {
guess = num/2;
// Notice the slight change in the while condition.
do {
r = num/guess;
g1 = guess;
guess = (guess+r)/2;
error = (guess-g1)/guess;
if (error < 0) {
error = -error;
}
} while(error >= 0.01);
}
// Finally, print the result.
System.out.println(
"The square root of the number " + num +
" is equal to " + guess
);
}

Better way of calculating sum of even ints

I'm trying to write a programme to prompt the user to input an int which is above or equal 2. From this input the programme must then calculate and print the sum of all the even integers between 2 and the entered int. It must also produce an error message if the inputted int is below 2. I've made a programme for it that works but am just wondering if you guys could find a better way of doing it? I'm sure there is but I can't quite seem to find a way that works!
Here's what I did:
import java.util.Scanner;
public class EvenSum {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer which is above 2.");
int number = scan.nextInt();
int divnum = number / 2;
int divnum2 = divnum + 1;
int sumofeven = divnum * divnum2;
if(number >= 2)
System.out.println("The sum of the even integers between the number is "+
sumofeven);
else
System.out.println("Invalid number entered.");
}
}
Note: do not use this example in a real context, it's not effective. It just shows a more clean way of doing it.
// Check the input.
if (number >= 2)
System.out.println(sum(number));
}
// Will find the sum if the number is greater than 2.
int sum(int n) {
return n == 2 ? n - 2 : n % 2 == 0 ? n + sum(n - 2) : sum(n - 1);
}
Hope this helps. Oh, by the way, the method sum adds the numbers recursively.
Sorry, but I had to edit the answer a bit. There might still be room for improvement.
Why do it with a loop? You can actually calculate it out. Let X be the number they choose. Let N be the largest even number <= X. (N^2+2*N)/4 will be your answer.
Edit: just saw the answer above me. He is right. I gave the function I suppose.
Why use a loop at all? You are computing the sum of:
2 + 4 + ... n, where n is a positive even number.
This is a very simple arithmetic progression.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer which is above 2.");
int number = scan.nextInt();
if (number >= 2) {
int sumofeven = 0;
for (int i = 2; i <= number; i += 2) {
sumofeven += i;
}
System.out.println("The sum of the even integers between the number is " + sumofeven);
} else {
System.out.println("Invalid number entered.");
}
}

Categories

Resources