Sum the first N numbers in java - java

Hello, I am new to programming and I am trying to write a small program where it will calculate the sum for first N numbers. The problem is it does not work for even numbers. I have not managed to figure out why.
My code is as follow:
int n = Integer.parseInt(args[0]);
int sum = (1+n)/2*n;
System.out.println(sum + " is the sum of first " + n + " numbers");

It doesn't work for even n because (n+1)/2 is truncated to an int.
This means that if, for example, n=4, (n+1)/2 results in 2 instead of 2.5, so when you multiply it by n, you get 8 instead of the desired 10.
You can overcome this problem simply by changing the order of the operations. If you first multiply n by (n+1), the result is guaranteed to be even, so dividing it by 2 will produce the correct answer.
int sum = n*(1+n)/2;

You have integer division with (1+n)/2. If your number is even, then (1+n) is odd and the division by 2 will truncate any decimal result, so that an int divided by an int is still an int.
Multiply by n first, then divide by 2. This ensures that the product is even before dividing, so the result is correct.
int sum = (1+n) * n / 2;

One can use ((n * (n + 1)) / 2). But I think the following will work without overflow errors for a few additional values of n:
if ((n & 1) == 0) {
sum = ((n >> 1) * (n + 1));
} else {
sum = (n * ((n + 1) >> 1));
}

Related

How to add 'n' amount of odd integers?

I'm trying to write a program that computes the sum of the first n positive odd integers.
I'm having trouble figuring out how to incorporate n into finding the sum. I already have a do/while loop to ensure I get a positive value when assigning n value. I know that I have to use a for loop but I'm not really sure how I would do that.
Scanner input = new Scanner(System.in); // open input stream
String cleanUpStr; // clean kbd buffer
int n; // number
int sum; // sum of numbers
int cntr; // counter for loop
cleanUpStr = "nothing yet";
n = 0;
sum = 0;
cntr = 0;
//prompt user for the value of n
// use a loop to ensure a positive output
do
{
System.out.println("Enter the value of n");
n = input.nextInt();
cleanUpStr = input.nextLine();
// print error if n is invalid
if (n < 0)
{
System.out.println("Invalid n value of " + n + ", try again.");
} // end if
}while(n < 0);
for(cntr = 0; cntr < n; ++cntr)
{
} // end for
} // end main
For example: if n = 5, then this should compute 1 + 3 + 5 + 7 + 9.
The nice thing about this problem, is that you don't need to write a loop! The sum of the first n positive odd integers is the square of n (written throughout this post as n^2). This is how you express the sum in terms of n. So the following will suffice:
// Calculate the sum of first n positive odd integers by using the n^2 formula.
public static int sumOddIntegers(int n) {
return n*n;
}
If you're set on using a loop, you can do the following by observing that the i-th positive odd integer can be calculated using the formula (2i-1):
// Calculate the sum of first n positive odd integers by adding each number iteratively in a loop.
public static int sumOddIntegers(int n) {
int oddSum = 0;
for (int i = 1; i <= n; i++) {
oddSum += (2*i - 1);
}
return oddSum;
}
To visualize this, consider the following examples:
n = 1 List: {1} S(n) = 1 = 1 = n^2
n = 2 List: {1, 3} S(n) = 1 + 3 = 4 = n^2
n = 3 List: {1, 3, 5} S(n) = 1 + 3 + 5 = 9 = n^2
n = 4 List: {1, 3, 5, 7} S(n) = 1 + 3 + 5 + 7 = 16 = n^2
n = 5 List: {1, 3, 5, 7, 9} S(n) = 1 + 3 + 5 + 7 + 9 = 25 = n^2
And so on...
Here is a proof by induction showing that the sum of the first n positive odd numbers is n^2. I'm new to Stack Overflow, so I hope my formatting is legible. If it can be improved, please feel free to suggest edits :) It seems like Stack Overflow doesn't support LaTeX style exponent and subscript formatting, so I did my best.
Proof
P(n): The sum of the first n positive odd integers is n^2.
Base Case
P(1): n = 1
The n = 1 case is trivial. The list of the first n positive odd integers is simply {1}. Therefore the sum of the first n positive odd integers is 1. Since 1 = n = n^2, the predicate P(1) holds true.
Inductive Hypothesis
Assume that P(k) holds for any arbitrary positive integer k > 0.
Inductive Step
Given P(k), we will prove that P(k+1) also holds true. In words, if the sum of the first k positive odd integers is k^2, then the sum of the first (k+1) positive odd integers is (k+1)^2.
As part of this proof, assume the following lemma.
Lemma 1: The nth positive odd integer can be expressed as 2n-1.
If P(k) holds, then the sum of the first k positive odd integers {a_1, ... a_k} is k^2 where the element a_k is expressed as 2k-1 (by Lemma 1). It follows that adding the (k+1)st positive odd integer, a_(k+1) to the list of the first k positive odd integers will produce a list of the first (k+1) positive odd integers as follows: {a_1, ... a_k, a_(k+1)}. Therefore, the sum of this list of the first (k+1) positive odd integers will be equal to the sum of the list of the first k positive odd integers plus the value of a_(k+1), the (k+1)st positive odd integer. By Lemma 1, the (k+1)st positive odd integer is expressed as 2(k+1)-1 = 2k+1.
Let S(k) = the sum of the first k positive odd integers. Therefore, S(k) = k^2. The above statements imply that
S(k+1) = S(k) + a_(k+1), adding the (k+1)st positive odd integer
S(k+1) = S(k) + (2(k+1)-1), by Lemma 1
S(k+1) = S(k) + (2k+1)
S(k+1) = k^2 + (2k+1), by inductive hypothesis
S(k+1) = k^2 + 2k + 1
S(k+1) = (k+1)^2, by factoring
We have therefore shown that if S(k) = k^2, then S(k+1) = (k+1)^2. This shows that P(k) -> P(k+1).
By induction, we have proved that P(n) holds for any positive integer n > 0.
The sum of the first n positive odd integers is therefore n^2. QED.
Proof of Lemma 1:
Here is a proof of this by induction.
P(n): The nth positive odd integer, a_n, can be expressed as 2n-1.
Base case: P(1): 1 is the first positive odd integer (case n = 1).
1 = 2(1)-1 = 1.
Therefore, a_1 = 1 = 2n-1. Correct.
Inductive Hypothesis: Assume P(k) holds.
Inductive Step: If P(k) holds, then P(k+1) holds.
If P(k) holds, then the kth positive odd integer can be expressed as 2k-1. By addition, the next positive odd integer (the (k+1)st positive odd integer), would be (2k-1) + 2.
= (2k-1) + 2
= 2k-1 + 2
= 2k+2 - 1
= 2(k+1) -1
We have shown that P(k) -> P(k+1). Therefore, by induction, P(n) holds for all integers n > 0. QED.
Good luck! Hope this was helpful :)
Stream is good, but if you're a beginner a plain old for loop is your best friend.
public static int sumForOddNumbers(int total) {
int sum = 0;
for(int i = 0, odd = 1; i < total; i++, odd += 2) {
sum += odd;
}
return sum;
}
Java stream API suggests quite clear solution:
IntStream.iterate(1, i -> i + 2)
.limit(n)
.sum();
More about IntStream by link
While streams would be a great way to go about this if you were concerned with functional programming, just learning Java I would suggest the below.
int oddValue = 1;
int answer = 0;
for(cntr = 0; cntr < n; ++cntr)
{
//adds oddvalue to your answer
answer += oddValue;
//adds two to odd value (next odd)
oddValue+=2;
}
There are numerous approaches to this problem.
The way you're thinking about it, yes, you can use a loop. Generally, you have a loop counter and some maximum.
The first observation to make is that odd numbers are written in the form 2k-1. Such as k=3, 2 * 3 - 1 = 5, i.e., 5 is the 3rd odd number.
Given this, you can write a loop for k, as follows:
for (int k = 1; k <= n; k++) {
int oddNumber = 2 * k - 1; // the kth odd number
}
You can then sum these up.
Another way to do it is the way #Ruslan has shown, which uses a lambda expression to encode a similar idea. It walks over a list of integers, starting at 1 and stepping 2 each time: 1, 3, 5, 7, .... This can be done in a loop as well:
for (int oddNumber = 1; oddNumber <= (2*n - 1); oddNumber += 2) {
// calculate a sum here
}
Notice that this 2*n - 1 expression came up again. We're counting odd numbers until we reach the nth one.
There are also ways to do this without loops, such as realizing the following pattern:
1 = 1
1 + 3 = 4
1 + 3 + 5 = 9
1 + 3 + 5 + 7 = 16
1 + 3 + 5 + 7 + 9 = 25
This means that the sum of the first n odd numbers is just n^2. No loops needed. (Proofs for this are available on your favourite math website.)

How to get even/odd random number divisible by first random number

I have following code:
quesPart1 = ran.nextInt((numbersBetween - 2) + 1) + 2;
quesPart2 = ran.nextInt((numbersBetween - 2) + 1) + 2;
if(quesPart2 > quesPart1)
{
int placeHolder = quesPart1;
quesPart1 = quesPart2;
quesPart2 = placeHolder;
}
//if first part is even
if(quesPart1 % 2 == 0)
{
if(quesPart2 % 2 != 0)
{
--quesPart2;
}
}
else
{
if(quesPart2 % 2 == 0)
{
++quesPart2;
}
}
Above code make sure that if quesPart1 is greater than quesPart2 and both are even or both are odd numbers. Now i want to get only random numbers which are also divisible by one another. Like if i divide quesPart1 by quesPart2 i get integer not decimal number. Any ideas how i can do that without adding too much complexity to above code.
You can do something like:
int div = quesPart1 / quesPart2;
quesPart1 = div * quesPart2;
add this code at the bottom of your code.
Like if i divide quesPart1 by quesPart2 i get integer not decimal number.
Keep it simple: generate random numbers and take their product. Example:
quesPart2 = ran.nextInt(UPPER_BOUND);
int temp = ran.nextInt(UPPER_BOUND);
questPart1 = temp * quesPart2;
Specifying the range, as in the original question, is left an an exercise to the reader. (What, you didn't think I was going to do all the thinking for you, did you? ;-)
Look into the modulus operator, a % b. It returns the left over amount when a is divided by b. When b cleanly divides into a, such that there is no decimal part, a % b will be zero.
In order to generate a number that is divisible by another, given two random numbers, a and b, simply multiply a by b. This will give you c, a number that is a multiple of both a and b, and therefore dividable by both cleanly without remainder.
I have come up with this simple function and a do while loop that is easy to implement.
// This is a simple function to set the min and max integers you want
const getRandomIntInclusive = (min, max) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
//Define some variables variables
let firstNo = 0
let secondNo = 0
let isDivisible = 0;
//generate random ints until first number is divisible to second number
do {
//get random int between 1-9 for the first and second integer
firstNo = getRandomIntInclusive(1, 9)
secondNo = getRandomIntInclusive(1, 9)
isDivisible = firstNo % secondNo; //Check if it's fully divisible
}
while (isDivisible != 0) //Run until it is fully divisible
To generate Random numbers in java you can use ran.nextInt() or please refer to this link to see how to generate random numbers.
store those 2 random numbers (as num1 and num2).
To verify whether the solution after dividing num1 and num2 is integer or not, use this method:
sol = num1 / num2
if (sol == (int)sol)
{
... //true if the solution is an integer
}

Algorithm to solve an equation

I have this problem for the course "Algorithm and data structures"
You have a equation x^2+s(x)+200·x=N, where x and N are natural numbers and S(x) is the sum of digits of number x.
On the input we have N and A, B such that A≤B and A, B≤1,000,000,000. You need to check if there is a natural number x in the interval [A, B] that solves the equation. If found you need to return that number, otherwise return -1.
Example Input:
1456
10 80
Output
-1
I managed to solve this problem by using some math and a bit modified version of brute force algorithm. But are there any more effective(algorithm based) ways to solve this problem?
This is my code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Range {
static int proveri(long N, long A, long B) {
long res = 0;
long start = (long)((-200 + Math.sqrt(4*N + 4))/2);
//System.out.println(start);
for (long i = Math.max(A, start); i <= B; i++) {
res = i * i + S(i) + 200 * i;
if(res == N)
return (int)i;
if(res > N)
return -1;
}
return -1;
}
static int S(long x) {
int sum = 0;
while(x > 0) {
sum += x % 10;
x /= 10;
}
return sum;
}
public static void main(String[] args) throws Exception {
int i,j,k;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
long N = Long.parseLong(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
long A = Long.parseLong(st.nextToken());
long B = Long.parseLong(st.nextToken());
int res = proveri(N, A, B);
System.out.println(res);
br.close();
}
}
Here's a way where you can cut down on the amount of numbers you have to search.
Consider the equation anxn +
an-1xn-1 + ... + a1x + a0 = 0.
The rational root theorem states that if x = p/q is a solution,
then p divides a0 and q divides an
In your case, an is 1 and a0 is equal to S(x)-N. Thus, we know that any solution must divide S(x)-N.
This is where ben75's tip comes in. Since S(x) can't be bigger than 81, we can loop through all of the possible values of S(x), and solve separately. Something like this:
for each possible value of S(x)
loop through every factor x of S(x) - N
check if it is between A and B, if its digits sum to S(x)
and if it is a solution to x*x + 200x + S(x) = N.
if it is, return it.
return -1
There's also a pretty slick way for you to loop through all of the factors of a number, but I'll let you work that one out for yourself since this is for a course. My hint there is to look at the prime factorization of a number.
For the equation x^2+s(x)+200·x=N, consider
x^2 + 200·x + (N - s(x)) = 0
For a solution to a*x^2 + b*x + c = 0 equation with integer solutions, we need to have:
b^2 - 4*a*c >= 0 and must be a perfect square
Hence 200^2 - 4 * (N - s(x)) >=0 and a square or
10000 >= (N - s(x)) and (10,000 - (N - s(x)) must be a square. The square value is therefore less than 10,000 and hence there can be at most 100 values you need to check. With proper values of N it can be much lesser.
Also note that since N < 10,000, s(x) can be at most 36. These should cut down the range quite a bit.

Java program divisible by three without using modulus

I'd like to create a program wherein a user will type a number and the program will tell if it is divisible by 3 or not. But %, /, +, * can't be used in the program. Anybody here got some ideas how to do that?
public static void main(String[] args) {
String number = "123456";
int sum = 0;
for (char c : number.toCharArray()) {
sum = sum - (0 - c) - '0';
while (sum >= 3) {
sum -= 3;
}
}
System.out.print("divisible by 3? ");
System.out.println(sum == 0);
}
Alternatively you can keep subtracting 3 until your number is either 0 (divisible by 3) or <0: not divisible by 3.
ps: it needs to be adapted if you want to deal with negative numbers
easy peasy...
boolean divisibleBy3(int n) {
return (""+n).matches("([0369]|[147]([0369]|[147][0369]*[258])*([" +
"258]|[147][0369]*[147])|[258]([0369]|[258]" +
"[0369]*[147])*([147]|[258][0369]*[258]))*");
}
A number is divisible by there if the sum of all the digits is also divisible by 3. You can iterate the process until you have a number smaller than 10 and compare it which known divisors (3,6 and 9)
Since it is most likely a game or homework and you can use + you can simple use minus two times: a - - b is equivalent to a + b
Assuming you can use the - operator then
bool divBy3(int n)
{
while (n >= 0)
{
n -= 3;
}
return n == 0;
}
This will return true if n is exactly divisible by 3, false otherwise. Note that this is really inefficient! Using the % operator would be far better.
Divisibility by 3 in binary representation is like divisibility by 11 in decimal (10+1): sum of digits in even places minus sum of digits on odd places is in turn divisible by 3 (maybe 0).

Sum of numbers under 10,000 that are multiples of 3, 5 or 7 in Java

I know how to get the program to add up the sums of the multiple for each of 3, 5 and 7, but I'm not sure how I'd get the program to only use each number once. For example, I can get the program to find out all of the numbers and add them up for 3 and then do the same for 5, but then the number 15 would be in the final number twice. I'm not sure exactly how I'd get it to only take the number once. Thanks for any help.
While the generate-and-test approach is simple to understand, it is also not very efficient if you want to run this on larger numbers. Instead, we can use the inclusion-exclusion principle.
The idea is to first sum up too many numbers by looking at the multiples of 3, 5 and 7 separately. Then we subtract the ones we counted twice, i.e. multiples of 3*5, 3*7 and 5*7. But now we subtracted too much and need to add back the multiples of 3*5*7 again.
We start by finding the sum of all integers 1..n which are multiples of k. First, we find out how many there are, m = n / k, rounded down thanks to integer division. Now we just need to sum up the sequence k + 2*k + 3*k + ... + m*k. We factor out the k and get k * (1 + 2 + ... + m).
This is a well-known arithmetic series, which we know sums to k * m * (m + 1)/2 (See triangle number).
private long n = 9999;
private long multiples(long k) {
long m = n / k;
return k * m * (m + 1) / 2:
}
Now we just use inclusion-exclusion to get the final sum:
long sum = multiples(3) + multiples(5) + multiples(7)
- multiples(3*5) - multiples(3*7) - multiples(5*7)
+ multiples(3*5*7);
This will scale much better to larger n than just looping over all the values, but beware of overflow and change to BigIntegers if necessary.
The easiest approach would be to use a for loop thus:
int sum = 0;
for(int i=1; i<10000; i++)
{
if (i % 3 == 0 || i % 5 == 0 || i % 7 == 0)
sum += i;
}
Use a Set to store the unique multiples, and then sum the values of the Set.
I would use a Set. This way you are guaranteed that you won't get any duplicates if they are your main problem.
One simple solution would be to add each number thats a multiple of 3,5, or 7 to an Answer list. And then as you work thru each number, make sure that its not already in the answer list.
(pseudo-code)
List<int> AnswerList;
List<int> MultiplesOfFive;
List<int> MultiplesOfSeven;
List<int> MultiplesOfThree;
for (int i = 0 ; i < 10000; i++)
{
if ( i % 3 == 0 && AnswserList.Contains(i) == false)
{
MultiplesOfThree.Add(i);
AnswerList.Add(i);
}
if ( i % 5 == 0 && AnswserList.Contains(i) == false)
{
MultiplesOfFive.Add(i);
AnswerList.Add(i);
}
if ( i % 7 == 0 && AnswserList.Contains(i) == false)
{
MultiplesOfSeven.Add(i);
AnswerList.Add(i);
}
}
for the solution that loops 1 to 1000 use i<=10000 otherwise it'll skip 10000 itself which is a multiple of 5. Apologies, for some reason i can't post this as a comment

Categories