Finding the sum of the odds in between two numbers inclusive - java

I am writing a simple program to find the sum of the odd numbers in between two inputted numbers, and I would appreciate any feedback. I've been working at this problem for a long time, and I could use some expertise.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("#1: ");
int num1 = s.nextInt();
System.out.print("#2: ");
int num2 = s.nextInt();
int sum = 0;
for(int i= num1; i<(num2-num1); i++){
if (i%2 != 0){
sum+=i;
}
}
System.out.print();
}
}

There are a few simple errors that you can fix in your code here. First, it should not be (num2-num1), but rather just num1. Also, make sure you print your result in the last statement. In contrast, there are many other ways to attack this problem, but if you fix these few issues, your simple method will work just fine.

I would test if num1 is even first, if it is add one to make it odd (otherwise, it's already odd). Then increment by 2, so you know every i is odd. Next, your loop test should be <= num2 (not < num2 - num1), because you want the range from num1 to num2 inclusive. Finally, don't forget to actually print the result. Like,
if (num1 % 2 == 0) {
num1++;
}
int sum = 0;
for (int i = num1; i <= num2; i+=2) {
sum += i;
}
System.out.println(sum);
Alternatively, in Java 8+, you might do it with an IntStream like
System.out.println(IntStream.rangeClosed(num1, num2).filter(x -> x % 2 != 0).sum());

You can also apply some math instead of looping through all the numbers, which is much more efficient and becomes a constant time algorithm instead of linear time.
To get the sum of the numbers you can multiply the average between both numbers by the count of elements in the range.
If any of both numbers is odd, you can add one, or substract one to reach the first even number in the range, so you calculate from an even to an even number.
Example: from 3 to 12, you will use 4 and 12. Average is 8. And you have (12-4)/2 + 1 = 5 even numbers in the range (the +1 is because it's inclusive range). The sum will be 8*5=40.
Which is true: 4+6+8+10+12 = 40

import java.util.Scanner;
class SumOfOdds
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print("#1: ");
int num1 = s.nextInt();
System.out.print("#2: ");
int num2 = s.nextInt();
if (num1 % 2 == 0)
{
num1++;
}
int sum = 0;
for (int i = num1; i <= num2; i+=2)
{
sum += i;
}
System.out.println(sum);
}
}

Related

Problem in code and need a short code to solve problem

fist thing first , the code :
package com.company;
import java.util.Scanner;
public class index {
public static void main (String[] args)
{
System.out.println("enter any three digit number ");
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
//let a= 2 7 4
int b= a%10;//4
int c=a/10;//27
int d= c%10;//7
int e=c/10;//2
//e=first num;
//d=middle num;
//b= last num ;
// for searching the greatest number
if (d>e && d>b )
System.out.printf(" the greatest number is %d%d%d",d,e,b);
else if(e>d && e>b )
System.out.printf(" the greatest number is %d%d%d",e,d,b);
else if (b>e && b>d )
System.out.printf(" the greatest number is %d%d%d",b,e,d);
// for the smallest number
else if(d<e && d<b && b>e)
System.out.printf(" the smallest number is %d%d%d",b,e,d);
else if(d<e && d<b && e>b)
System.out.printf(" the smallest number is %d%d%d",e,b,d);
else if (e<d && e<b && b>d)
System.out.printf(" the smallest number is %d%d%d",b,d,e);
else if(e<d && e<b && d>b)
System.out.printf(" the smallest number is %d%d%d",d,b,e);
else if (b<e && b<d && e>d)
System.out.printf(" the smallest number is %d%d%d",e,d,b);
else
System.out.printf(" the smallest number is %d%d%d",d,e,b);
}
}
now the problem:
this code is make to take number from the user as the input **of any three digit number ** and change it to the greatest number and smallest number ,
for example:
input number =274
output :
greatest number=742
smallest number=247
the above code is giving the greatest number but not the smallest number and the code is very lengthy ,
my output:
enter any three digit number
546
the greatest number is 654
so please help ,any error in code and if there is any short code then please help
I think that the problem is in the way of solution. As for me that is better to use some array or list and sort it. Something like that
public static void main (String[] args)
{
System.out.println("enter any three digit number ");
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int[] array = new int[3];
for (int i = 0; i < 3; i++) {
array[i] = a % 10;
a = a / 10;
}
Arrays.sort(array);
int smallest = 0;
int greatest = 0;
for (int i = 0; i < 3; i++) {
smallest += array[i];
if (i != 2) {
smallest *= 10;
}
}
for (int i = 2; i > -1; i--) {
greatest += array[i];
if (i != 0) {
greatest *= 10;
}
}
System.out.println(Arrays.toString(array));
System.out.println(smallest);
System.out.println(greatest);
}
May I suggest a whole different approach?
void printGreatestAndSmallest(int number) {
char[] digits = String.valueOf(number).toCharArray();
Arrays.sort(digits);
String smallest = new String(digits);
String greatest = new StringBuilder(smallest).reverse().toString();
System.out.println("Greatest number is " + greatest);
System.out.println("Smallest number is " + smallest);
}
What happens here, is that we convert the digits to a char[], which can be sorted using Arrays.sort(...). This way, the smallest digit comes in front, the largest at the end. The char[] is converted back to a string with the String(char[]) constructor.
That is the smallest value. The largest value is the reverse of it! We can get the largest number using StringBuilder's reverse() method.
Note that this code cannot handle negative numbers.
The problem with your current approach is that it contains a lot of repetitions, and is not quite flexible; it is bound to an input of exactly three digits.
In order to fix the issue your are facing, remove the else keyword from the line else if(d<e && d<b && b>e). Each if-elseif-else statement only executes a single branch, but you need two branches to be executed, one for the smallest number, and one for the greatest number.
Further:
Use descriptive variable names. You have a comment in your code:
//e=first num;
//d=middle num;
//b= last num ;
but why don't you rename e, d and b to firstDigit, middleDigit and lastDigit respectively?
Follow the Java Naming Conventions. Variable and method names are written in camelCase, and class names in PascalCase. So class index should be class Index. Also make sure to rename index.java to Index.java.
You are defining variables with almost the same function: in your case firstNum, middleNum and lastNum. They all allow to store a specific digit of the input number. In such a case, you should use an array instead of separate variables. Loops work well with arrays.
If your code somehow iterates over all possible permutations of some collection, using if-else statements, that is probably not the best way.
For example:
if (d>e && d>b )
else if(e>d && e>b )
else if (b>e && b>d )
You should ask yourself: should these digits be in a certain order? The answer here is yes, they need to be sorted from low to high (and high to low). In that case, you probably want to sort them.

How to divide a variable multiple times

I would appreciate any help.
So the prompt was to create a program with integers userNum and x as inputs and have the output be userNum divided by x a certain amount of times(in my case, let's say 4).
This is the code I have so far which works finely for dividing userNum by X but it only does it once when I need it be done however many times is specified. Any advice?
public class LabProgram
{
public static void main(String[] args)
{
int userNum;
int x;
Scanner scnr = new Scanner(System.in);
userNum = scnr.nextInt();
x = scnr.nextInt();
System.out.println(userNum / x);
}
}
If my input 2000 2, I only get 1000 as an output when my required output is 1000 500 250 125.
You will need to use some form of loop such as a for loop.
public static void main(String[] args)
{
int userNum;
int x;
int times;
Scanner scnr = new Scanner(System.in);
userNum = scnr.nextInt();
x = scnr.nextInt();
times = scnr.nextInt();
for(int i = 0; i < times; i++){
userNum /= x;
}
System.out.println(userNum);
}
You may want to make userNum a double as integer division will result in truncation of decimal values by removing the decimal portion.
I think it's time for you to use something called a 'loop'.
Something like:
for (int i = 0; i < 4; i++) {
}
Put some parts of your code inside this loop and magic will appear.
Here, You can use loops here if you want to divide number 4 times then you can use for loop and if you want to divide UserNum until value of UserNum is not equals to 0 then you can use while loop.

Output amount of primes in array

I'm kind of a newbie at Java, and not very good at it. It's a trial and error process for me.
I'm working on a Java program to output the amount of primes in an array. I can get it to output the primes, but I want to also output the quantity of primes. I tried to add each prime to an array list titled "primes" then return "primes.size()" at the end of my program. It doesn't work as intended. The count is actually off. When I create an array of 5 numbers, it outputs 3 primes, 2, 3, and 5. But then it says I have 4 primes. I think it might be counting 1 as a prime. Because when I create an array of 20, the prime numbers output 2,3,5,7,11,13,17 and 19. Then it says the total prime numbers = 9. It should be 8 though.
Here's my code
public class Prime {
public static void main(String[] args) {
int index = 0;
Scanner scan = new Scanner(System. in );
System.out.println("How big would you like the array? ");
int num = scan.nextInt();
int[] array = new int[num];
ArrayList < Integer > primes = new ArrayList < Integer > ();
//System.out.println("How Many threads? ");
//int nThreads = scan.nextInt(); // Create variable 'n' to handle whatever integer the user specifies. nextInt() is used for the scanner to expect and Int.
//Thread[] thread = new Thread[nThreads];
for (int n = 1; n <= array.length; n++) {
boolean prime = true;
for (int j = 2; j < n; j++) {
if (n % j == 0) {
prime = false;
break;
}
}
if (prime) {
primes.add(n);
}
if (prime && n != 1) {
System.out.println(n + "");
}
}
System.out.println("Total Prime numbers = " + primes.size());
System.out.println("Prime Numbers within " + array.length);
}
}
Forgive the sloppiness of it. I actually plan on adding multithreading to it, but I wanted to get this down first.
Any help would be greatly appreciated. Thanks.
You have included 1 in your array of primes, because you started the n for loop at 1. You don't print it because of the final if statement, but it's there in the ArrayList.
Start your n for loop with n = 2. As a consequence, you won't need the final if statement, because n won't be 1 ever. You could print the prime at the same time as you add it to the ArrayList.

Sum of Digits in Java

import java.util.Scanner;
public class CubesSum {
public static void main (String [] args){
int input;
System.out.println("Enter a positive integer:");
Scanner in = new Scanner(System.in);
input = in.nextInt();
int number = input; //number is a temp variable
int sum = 0;
while(number>0){
int t= number%10;
sum += t*t*t;
number = number/10;
}
System.out.println("The sum of the cubes of the digits is:" +sum);
}
}
Okay so I'm using a while loop. For part B which is to modify to determine what integers of two, three, and four digits are equal to the sum of the cubes of their digits. So for example, 371 = 3³+7³+1³. Can someone tell me how to do it? I need to wrap a for loop around my while loop...
Take the part of your code that computes the sum of the cubes of the digits of a number, and make that a function:
int sumOfCubedDigits(int number) {
int sum = 0;
// compute sum from number
return sum;
}
Then, loop through all the 2-to-4 digit numbers and check whether they equal the sum of the cubes of their digits:
for (int n = 10; n < 10000; n++) {
if (n == sumOfCubedDigits(n)) {
// do whatever with n
}
}
You could keep the sum-of-cubed-digits computation inside the for loop if you want, but it'd be a bit less readable.
Okay, so it looks like you haven't learned about function definitions yet. I shouldn't have assumed. Let's do it with a nested loop, then.
As you said, you need to wrap a for loop around your while. We need to consider all 2-to-4 digit numbers, so our loop will start at the first 2-digit number and end when it reaches the first 5-digit number:
for (int n = 10; n < 10000; n++) {
// More code will go here.
}
Inside the loop, we need to compute the sum of the cubed digits of n. The code you wrote earlier to compute that modifies the number it's operating on, but we can't modify n, or we'll screw up the for loop. We make a copy:
for (int n = 10; n < 10000; n++) {
int temp = n;
int sum = 0;
// Compute the sum of the digits of temp, much like you did before.
}
Finally, if the sum is equal to n, we do something to indicate it. Let's say your assignment said to print all such numbers:
for (int n = 10; n < 10000; n++) {
int temp = n;
int sum = 0;
// Compute the sum of the digits of temp, much like you did before.
if (sum == n) {
System.out.println(n);
}
}
For an arbitrary integer i, it's nth digit dn is, (being n=1 the rightmost digit)
dn = (i % (10^n)) / (10^(n-1)) // all integer operations
as you can see, you'll need to know beforehand the number of digits of your i, otherwise, yes, you'll need a loop
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter number : ");
int num = input.nextInt();
int temp = num, remainder;
int sum = 0;
while(temp %10 != 0){
remainder = temp %10;
sum = sum+ remainder ;
temp = temp/10;
}
System.out.println("Sum of digit : " + sum);
=====OUTPUT====
Please enter number : 123
Sum of digit : 6

not a statement error, illegal start of type

import java.util.*;
public class ulang {
public static void main(final String[] args) {
int a;
int b;
int sum;
Scanner scan = new Scanner(System.in);
System.out.println("Enter num 1: ");
a = in.nextLine();
System.out.println("Enter num 2: ");
b = in.nextLine();
{
sum = a + b;
}
for (i = 0; i < 5; i++) {
(sum >= 10)
System.out.println("Congratulations");
else
System.out.println("Sum of the number is Less than 10");
}
}
}
I'm weak on looping especially in Java. So I need some corrections on my coding, but I have no idea how to fix it.
The coding should run like this: User need to insert 2 numbers and the program will calculate the sum of both number. After that, the program will determine if the total of sum is >=10 or <10. If the sum >=10, "Congratulations" will appear but if it is <10, then "The sum of number less than 10" will appear. How to fix it?
This is the immediate problem:
(sum>=10)
I believe you meant that to be an if statement:
if (sum>=10)
Additionally:
You're trying to use an in variable, but the Scanner variable is called scan
Scanner.nextLine() returns a String - I suspect you wanted Scanner.nextInt()
Your for loop uses a variable that hasn't been declared. You probably meant:
for (int i = 0; i < 5; i++)
A few other suggestions though:
The sum isn't going to change between the loop iterations... why are you looping at all?
You've got a new block in which you're calculating the sum, but for no obvious reason. Why?
It's generally a good idea to declare variables at the point of initialization, e.g.
Scanner scan = new Scanner(System.in);
System.out.println("Enter num 1: ");
int a = scan.nextInt();
System.out.println("Enter num 2: ");
int b = scan.nextInt();
int sum = a + b;
Given that you want to take the same basic action (writing a message to the screen) whether or not the user was successful, you might consider using the conditional operator like this:
String message = sum >= 10 ? "Congratulations"
: "Sum of the number is Less than 10";
System.out.println(message);
That would then allow you to refactor the loop to only evaluate the condition once:
String message = sum >= 10 ? "Congratulations"
: "Sum of the number is Less than 10";
for (int i = 0; i < 5; i++)
{
System.out.println(message);
}
(sum>=10)
This line needs an if at the beginning, or it won't be read as a branch.
if (sum >= 10)
You also should name your main-class Ulang, because java class identifiers should start with an upper case letter, for readability.
The loop should look like the following:
for (int i = 0; i < 5; i++) {
The first part defines the counter and assigns zero to it. The second is your condition and the last counts for you.
for (int i = 0; i < 5; i++) {
if (sum >= 10)
System.out.println("Congratulations");
else
System.out.println("Sum of the number is Less than 10");
}

Categories

Resources