adding only odd numbers - java

So the question I'm trying to solve the user is supposed to enter any positive number. Then I'm trying to write a program that adds only the odd numbers up to the number the user enters and displays the total. So for example if the user enters 4 my program should add four odd numbers. 1 + 3 + 5 + 7 = 16. The only tools I have available are for statement, if, if/else if,while loop and println.
I can only figure out how to print out the odd numbers. I know I want to create a variable named total to store the value of adding up all the odd numbers but I don't know how that fits into the program.
import acm.program.*;
public class AddingOddNumbers extends ConsoleProgram {
public void run() {
int n = readInt("enter a positive nunber: ");
int total = 0;
for (int i = 0; i < n; i++) {
if (n == 1) {
println(1);
} else {
println((i * 2) + 1);
}
}
}
}

import acm.program.*;
public class AddingOddNumbers extends ConsoleProgram {
public void run() {
int n = readInt("enter a positive nunber: ");
int total = 0;
for (int i = 0; i < n; i++) {
if (n == 1) {
println(1);
} else {
println((i * 2) + 1);
total += (i * 2) + 1;
}
}
println("total : " + total);
}
}

sum = 0;
for (i = 1; i < n*2; i=i+2)
sum = sum + i;

This will give you the odd number sum.
if (n>0)
{
total=0;
for (int i = 1; i < n; i ++){
if (i%2 == 1)
total+=i;
}
}
If you want to inclusive of n, then change the condition to i<=n.

Maybe you know how to compute the sum of all numbers up to a given number n? The formula is quite simple: (n * (n+1))/2. Now getting the sum of only the odd numbers is a bit trickier but - no worries you can make use only of the previous formula for that. First notice that the sum of all even numbers up to a given number n is:
(((n/2)* (n/2+1))/2) * 2 if N is even(i.e. the sum of all numbers up to n/2 times two that is because you have 2+4+6+8+...N = 2*(1+2+3+...n/2))
((((n-1)/2)* ((n-1)/2+1))/2) * 2 if N is odd
In fact if you have integer division the formula is always: (((n/2)* (n/2+1))/2) * 2 = (n/2)* (n/2+1)
So to compute the sum of all the odd numbers up to n you simply subtract the sum of the even numbers from the sum of the all numbers:
(n * (n+1))/2 - (n/2)*(n/2+1)
In fact if you observe closely you will notice that the sum 1+3+...(2*n-1) always equals to n^2.
This answer should help you solve your problem in all languages and I am leaving the code to you. It is literally one line.

I would use a loop for the odd numbers as well.
for (int i = 0, j = 1; i < n; i++, j += 2) {
println(j);
total += j;
}
println(total);

int oddSum = 0;
for (int i = 0; i < n; i++){
oddSum = oddSum + (i*2) + 1;
}

Related

Java program that reads an integer value and prints the average of all odd integers between 0 and the input value, inclusive

Here is the entire question:
"Write a program that reads an integer value and prints the average of all odd integers between 0 and the input value, inclusive. Print an error message if the input value is less than 0. Prompt accordingly."
I can't seem to figure out how to get the math to work out in the for loop. I'm having trouble setting it up so that the loop increments in odds. I've tried a million different things and nothing has worked.
public static void main(String[] args) {
int value;
int oddAvg = 0;
int count = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer: ");
value = scan.nextInt();
while (value < 0){
System.out.println("Error: Input should not be less than 0");
System.out.print("Enter an integer greater than 0: ");
value = scan.nextInt();
}
for(){
}
System.out.println("The average of odd integers between 0 and " + value + " is " + oddAvg);
}
}
A trivial approach could be to just iterate from zero to the target number and check whether each number is odd or even:
int sum = 0;
int count = 0;
for (int i = 0; i <= value; i++) {
if (i % 2 != 0) {
sum += i;
count++;
}
}
int avg = sum / count;
But this, of course, is inefficient. A slightly better approach would be to start from the first odd number, 1, and increment it by 2 in each iteration, so you'd be iterating over just the odd numbers:
double sum = 0;
int count = 0;
for (int i = 1; i <= value; i += 2) {
sum += i;
count++;
}
int avg = sum / count;
Or, if you want to really be mathematically sound, you can utilize the fact that the odd natural numbers in a given range are uniformly distributed. Since this distribution is symmetric, the average equals the mean, and you don't need a loop at all:
int start = 1;
int end = value;
if (value % 2 == 0) {
value--;
}
int avg = (end + start) / 2;
General comment:
In this specific case the average would be an int, so I used ints throughout my examples. In the general usecase, you should probably use doubles to avoid mistakes of using integer division.
Here's a solution to your problem!
public static void main(String[] args) {
int input = 25; //this is whatever value you're going up to.
int accumulator = 0; //keep track of the total sum
for (int i = 0; i < input; i++) {
if (i % 2 == 1) { //if odd
accumulator+=i; // add to the running total sum
}
}
System.out.println(accumulator/(input/2)); //print out the total/num of numbers
}
You can try this if interested in Java 8. It is naive approach implementation.
int val = 0;
final OptionalDouble average = IntStream.rangeClosed(0, val)
.filter(n -> n % 2 != 0)
.average();
System.out.println(average);

Maximum Remainder

Maximum remainder
You are given a number N. Write a program to find a natural number that is smaller than N such that N gives the highest remainder when divided by that number.
If there is more than one such number, print the smallest one.
Can anyone help I think I'm missing something like if 2 numbers will have same reaminders my code would overwrite the minDivisor to the upper value
static int findRemainder(int num){
int maxRemainder=0;
int minDivisor=0
int answer=0;
for(int i = 1; i<num; i++){
if(maxRemainder <= (num % i)) {
maxRemainder = num % i;
if(minDivisor < i && maxRemainder == num%i) {
} else {
minDivisor = i;
}
}
return minDivisor;
}
}
Check this out:
int largestRemainder = c % ((c/2) + 1);

Effective way of find Total number of even divisors of the number

I have to find number of even number of divisor of given number. For this i tried.I am getting correct output but i am getting time complexity more than required.Question :- First line contains the number of testcases T, followed by T lines each containing an integer N output should be - For each testcase, print the required answer in a single line.How can i reduce complexity for this given code.Or can anyone please suggest more efficient way...
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class TestClass {
public static void main(String args[]) throws Exception {
// Read input from stdin and provide input before running
String frt = "";
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int T = Integer.parseInt(line);
int[] inp = new int[T];
for (int i = 0; i < T; i++) {
int x = Integer.parseInt(br.readLine());
inp[i] = x;
}
int[] ans = new int[T];
int count = 1;
for (int i = 0; i < T; i++) {
int x = inp[i];
if (x % 2 == 0) {
for (int j = 2; j <= x / 2; j = j + 2) {
if (x % j == 0)
count++;
}
} else
count = 0;
ans[i] = count;
}
for (int i = 0; i < T; i++)
System.out.println(ans[i]);
}
}
import java.io.*;
class Ideone
{
public static void main (String[] args) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
int i,j,k,n;
int[] inp = new int[T];
for (i = 0; i < T; i++) {
inp[i] = Integer.parseInt(br.readLine());
}
//Find all the primes numbers till the square-root of 10^9.
int MAX, root, arrLen;
MAX=1000000000;
arrLen=(int)Math.sqrt(MAX); // arrLen=31622
boolean[] primes=new boolean[arrLen+2]; // No need to find all the primes numbers till MAX
primes[0]=primes[1]=false;
for(i=2;i<arrLen;i++)
primes[i]=true;
// Using Sieve of Eratosthenes
// Square root of 31622 is 177.8
root=(int)Math.sqrt(arrLen); // root=177
for(i=2;i<=root;i++)
{
if(primes[i])
{
n=i*i;
k=0;
//arrLen is the length of primes array.
for(j=n; j<arrLen; k+=1, j=n+(i*k))
primes[j]=false;
}
}
int[] ans = new int[T];
for( i = 0; i < T; i++) {
n = inp[i];
if(n%2==1)
{
ans[i]=0; // Odd numbers will have 0 even divisors
}
else
{
int[] facts=new int[50];
for(k=0;k<50;k++)
facts[k]=1;
facts[0]=0; // fact[0] will contain the highest power of 2 that divides n.
while(n%2==0)
{
facts[0]+=1;
n=n/2;
}
// Prime factorizing n
j=1;
for( k=3; k<arrLen; k+=2)
{
if(primes[k] && n%k==0)
{
while(n%k==0)
{
facts[j]+=1;
n=n/k;
}
j+=1;
}
if(n==1) // To check if n has been completely divided or not.
break;
}
if(n!=1) // To check if there is any prime factor greater than the square root of MAX.
{
facts[j]+=1;
j+=1;
}
int count=1;
for(k=0;k<j;k++)
count=count*facts[k];
ans[i]=count;
}
}
for ( i = 0; i < T; i++)
System.out.println(ans[i]);
}
}
I am of the feeling that this question might have been posted on any competitive coding platform, probably like HackerEarth. If so, then please don't post direct questions on StackOverFlow(in my opinion).
Anyways, I have tested my code and it runs correctly.
In questions where you are not able to reduce time complexity, first make sure that unnecessary objects are not created. Object creation in the memory is a time consuming operation. Avoid irrelevant creation of object and variables. The code above can still be optimized, but that will reduce it's readability. :)
Also before approaching a problem, try to figure out various test cases. Like odd numbers will have 0 even divisors. So by checking whether a number is odd, can reduce several operations.
A bit more explanation to the above code:
Number Of Divisor of A Number are: (N1+1)(N2+1)(N3+1).... Where N1,N2,N3 etc are Powers Of Prime Multiples of the number.
Now if N1 is for 2(the only even prime number),
then Number of Even Divisors of the Number are: N1*(N2+1)*(N3+1)...
In the facts[] array, facts[0] corresponds to N1, while N2, N3 etc are stored in facts[1],facts[2], etc.
facts[0] is initialized with 0, while others are initialized with 1.
The count stores the final product: N1*(N2+1)*(N3+1)... which is equal to the number of Even divisors of the original number.
There is a very simple trick for this,first compute the prime factorization of 720,which is 2^4×3^2×5,the total number of factors here is 3x2×5=30, and number of odd factors (number of factors of the odd primes)=3×2=6,subtracting gives number of even factors = 24.This method works for any number.
NOTE: If the number has no odd factors i.e,the prime factorization is of the form 2a,then the number of number of even factors is a and number of odd factors is 1.
My solution, shorter and simpler:
public class Solution {
public static int numberOfEvenDivisors(int n) {
if (n % 2 == 1)
return 0;
int evenDivisors = 0;
for (int i = 1; i < Math.sqrt(n) + 1; i++) {
if ((i % 2 == 0) && (n % i == 0))
evenDivisors++;
if ((n % (n / i) == 0) && (n / i) % 2 == 0)
evenDivisors++;
if ((i * i == n) && (i % 2 == 0))
evenDivisors--;
}
return evenDivisors;
}
public static void main(String[] args) {
//test here
}
}
Here is short explanation:
When n is odd we return 0, there are no even divisors.
In the first if we check whether i is a divisor and whether i is even. When yes, wo do increment the divisors counter. Note that we start with 1. This is necessary because here we know that n is even and n is its own divisor.
In second if we increment divisors counter if n / i is even and i is a divisor. If i is even, we counted it already in first if. And we know that (n/i) >= i, because we count i only up to square root of n.
And in the last, third if we check the case whether i is a even divisor that is square root of n (for example i == 4, n == 16). Here we decrement number of divisors because we do not want to count same divisor twice. That is.
P.S. We assume n >= 1.
This for loop
for (int i = 0; i < T; i++) {
int x = inp[i];
if (x % 2 == 0) {
for (int j = 2; j <= x / 2; j = j + 2) {
if (x % j == 0)
count++;
} else
count = 0;
ans[i] = count;
}
could be changed to
for (int i = 0; i < T; i+=2) {
int x = inp[i];
for (int j = 2; j <= x / 2; j = j + 2) {
if (x % j == 0)
count++;
if(count != 1)
count = 0;
ans[i] = count;
}
so that it will make the for loop run half as many times.

How to calculate the average of even and odd numbers in an array?

As a class exercise I have to code using methods a program that:
1) Calculates the average of even and odd numbers in an array.
I expect on using one method to find the average of even and odd numbers. However, I'm having trouble on returning the right average. For example, if I enter only odd numbers I get an error, and vice versa.
This error:
"java.lang.ArithmeticException: / zero"
Also, if it were possible I would like to get some help on coding the rest of the exercise which asks for:
2) Print the highest and lowest number in the array
3) Allow the user to modify any of the numbers of the array
So far I have this code:
public static void main (String args[]){
int x[] = new int[4];
Scanner input = new Scanner(System.in);
for(int i = 0; i < x.length ; i++){
System.out.println("Enter a number: ");
x[i] = input.nextInt();
}
System.out.println("Average of even numbers: " + getAverage(x));
System.out.println("Average of odd numbers: " + getAverage(x));
}
public static int getAverage(int a[]){
int add_even = 0;
int counter_even = 0;
int average_even = 0;
int add_odd = 0;
int counter_odd = 0;
int average_odd = 0;
for(int i = 0; i < a.length; i++){
if(a[i] % 2 == 0){
add_even += a[i];
counter_even++;
}
else if(a[i] % 2 == 1) {
add_odd += a[i];
counter_odd++;
}
}
if (add_even % 2 == 1 && add_odd % 2 == 1){
average_even = 0;
average_odd = add_odd / counter_odd;
return average_even;
}
else if (add_even % 2 == 0 && add_odd % 2 == 0){
average_even = add_even / counter_even;
average_odd = 0;
return average_even;
}
else{
average_even = 0;
average_odd = add_odd / counter_odd;
return average_odd;
}
}
Thank you!
Your get average looks more complicated then it needs to be.
First off the getAverage(x):
System.out.println("Average of even numbers: " + getAverage(x));
System.out.println("Average of odd numbers: " + getAverage(x));
will return the same value, so if you wanted to get the average for odds or evens the method should require a boolean arg to represent odd or even.
In your method you should loop through all the numbers and check if it is even. If it is even and you are averaging evens add it to a "total" and add one to a counter. At the end divide "total" by the counter and return the value. The average will most likely include a decimal value, so you should return a double or a float.
Example:
public static double getAverage(int a[], boolean even){
double total = 0;//These are doubles so dividing later does not require casting to retain a decimal (this can be an int if you only want to return integers)
double counter = 0;
for(int i = 0; i<a.length; i++){
if(a[i] % 2 == 0 && even){//even
counter++;
total += a[i];
}else{//odd
counter++;
total += a[i];
}
}
if(total == 0){//Avoid dividing by 0.
return 0; //You can also throw an exception instead of returning 0.
}
return total / counter; //Returns the average for even or odd numbers.
}
For the second part of your question you need to loop through the numbers and find the highest and lowest while looping.
Example:
int highest = 0;
int lowest = 0;
for(int i = 0; i<x.length; i++){
if(x[i] > highest){
highest = x[i];
}
if(x[i] < lowest){
lowest = x[i];
}
if(i == 0){
highest = x[i];
lowest = x[i];
}
}
You have a divide by zero error cropping up here.
else if (add_even % 2 == 0 && add_odd % 2 == 0){
average_even = add_even / counter_even;
average_odd = 0;
return average_even;
}
0 % 2 == 0 so even if add_even is 0 (and as a result, so is counter_even) you're attempting to use it to divide. You'll need to account for that in your code by checking if counter_even is 0.
else if (counter_even != 0 && add_even % 2 == 0 && add_odd % 2 == 0){
1)Using one method to get the average of the even and odd numbers isn't proper because you only return one int. It would be simpler to use two methods but if you're insistent on using one method you could add a boolean as a parameter like this to decide which to do. To handle the ArithmeticException just return 0 if there are no values.
public static int average(int[] n, boolean even) {
int total = 0;
int count = 0;
for (int i = 0; i < n.length; i++) {
if (even == (n % 2 == 0)) {
total += n;
count ++;
}
}
if (count == 0)
return 0;
return total / count;
2)To check find the max and min value simply loop through the array like this
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int i = 0; i < x.length; i++) {
if (x[i] < min)
min = x[i];
if (x[i] > max)
max = x[i];
}
3)To allow the user to modify the array, you could print the values and prompt them as to which value they would like to change like this.
System.out.print("Array: ");
for (int i = 0; i < x.length; i++) {
System.out.print(i + ",");
}
System.out.println();
System.out.println("Which value would you like to change?");
int index = input.nextInt();
System.out.println("What do you want the new value to be?");
int value = input.nextInt();
You can then run a method that changes the value of the array
edit(x, index, value);
public static int edit(int[] n, int index, int value) {
n[index] = value;
return n;
}
I used JS for this task, you can just rewrite my code to Java language.
A number is divisible by 2 if the result of its division by 2 has no
remainder or fractional component - in other terms if the result is an
integer. Zero is an even number because when 0 is divided by
2, the resulting quotient turns out to also be 0 - an integer (as a
whole number that can be written without a remainder, 0 classifies as
an integer).
function compareEvenOddAverage(arr) {
let even = 0,
odd = 0,
evenCounter = 0,
oddCounter = 0,
str = '';
for (let i = 0; i < arr.length; i++) {
if (arr[i] % 2 === 0) {
even += arr[i];
evenCounter++;
} else {
odd += arr[i];
oddCounter++;
}
}
if (even / evenCounter > odd / oddCounter) {
str += 'Average value of even numbers is greater';
} else if (even / evenCounter < odd / oddCounter) {
str += 'Average value of odd numbers is greater';
} else {
str += 'Average values are equal';
}
return str;
}
console.log(compareEvenOddAverage([0, 1, 2, 3, 4, 5]));

Add two array elements using loop

I am trying a task with arrays: add two elements and check if the sum is less than or equal to 50. If the condition is satisfied, it should break.
Example program:
public class HelloWorld {
public static void main(String []args)
{
int[] nums = new int[2];
for (int i = 0; i < 100; i++)
{
nums[i] = i + 1;
System.out.println(i);
}
System.out.println(nums[1]);
System.out.println(nums[2]);
if (nums[0]+nums[1]<=50)
{
System.out.printf("Sucessfully finished");
}
}
}
Of course, my program is not working. I want i value to store in the two elements
nums[0] = 1 and nums[1] = 2. I also want to add these two elements and check if the sum is less than or equal to 50. I have allocated two elements in the array which means nums want to add and check the current two elements of i and clear and adds next two elements and check if its less than or equal to 50.
nums[0]=1;
nums[1]=2; check <=50 . fails clear the the array elements and store next i value
nums[0]=3;
nums[1]=4; check <=50 . fails clear the the array elements and store next i value
...
nums[0]=25;
nums[1]=26; check <=50 .
There are a lot of ways to do this but here is a nifty trick that solves exactly this kind of problem.
int[] nums = new int[2];
for (int i = 0; i < 100; i++) {
nums[i % nums.length] = i + 1;
if (nums[0] + nums[1] <= 50) {
System.out.println("sum is less than or equal to 50");
break;
}
}
What the mod operator (%) does is calculate the remainder of i based on the array's length. This ensures that i goes from 0 to 99 but the array index always "resets" and stays within the range of the array. For example after i == 0 and i == 1, i will be incremented to out of bounds at i == 2 but 2 % 2 == 0. When i == 3, 3 % 2 == 1 and so on.
But as a side note, the condition you've described ("if the sum is less than or equal to 50...it should break") will be satisfied immediately (sums 1 at nums[0] and 0 at nums[1]) and the loop will not execute past the first iteration (i == 0). I'm not sure that's what you are wanting. Do you mean "not less than or equal to 50"?
int[] nums = new int[2];
for (int i = 0; i < 100; i++) {
nums[i % nums.length] = i + 1;
if (nums[0] + nums[1] > 50) {
System.out.println("sum was NOT less than or equal to 50");
break;
}
}
As an alternate solution finding this result can be very much shortened to the following while loop:
int i = 0;
// note sum of two consecutive integers will never be even (never 50)
while (i + ++i < 50);
System.out.println("min increments with sum > 50 was " + (i - 1) + " and " + i);
The output is min increments with sum > 50 was 25 and 26.
I believe, you need 1 more for loop, to go about checking each num[i] + num[i+1]. You can do it in a single for loop as well, but kept the code as simple as possible for your clarity.(As you are new to java programming ;))
public class HelloWorld{
public static void main(String[] args) {
int[] nums = new int[100];
for (int i = 0; i < 100; i++) {
nums[i] = i + 1;
System.out.println(i);
}
for (int i = 0; i < 99; i++) {
System.out.println(nums[i]);
System.out.println(nums[i+1]);
if (nums[i] + nums[i+1] == 50) {
System.out.printf("Successfully finished");
}
}
}
}
I'm not sure if this is what you meant. Have a try.
public static void main(String[] args) {
int[] nums = new int[100];
nums[0] =1;
for (int i = 1; i < 100; i++) {
nums[i] = i + 1;
if ((nums[i] +nums[i-1]) >= 50) {
System.out.printf("Successfully finished");
}
}
}
I'm not entirely sure on what your end goal is. If you just want to add two numbers (i, and i+1) and see if they are less than 50 then you can use this.
for (int i =0; i < 100; i++) {
int j = i+1;
int total = i+j;
if((i+(i+1)) < 50) {
System.out.println("Numbers '" + i + "' and '" + j + "' equal '" + total + "'.");
}
}
This will print out all the pairs of numbers that add to less than 50 along with what they add to.
I accept that you're probably wanting something more. :)

Categories