java program to add up even number to 1 - java

I need help doing a program to add up even integers to 1
I need the computer to work out 1 + 3 + 7 + 13 + 21.... + n
n is whatever the user wants it to be
The sequence is adding up each even number, so for example, you start from 1 and add 2, which gets 3, then to 3 add 4, which gets 7, then to 7 add 6, which gets 13 and so on until you get to n.
I had a complete guess
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Odd4 extends JFrame implements ActionListener {
private JButton button;
private JPanel panel;
public static void main(String [] args) {
Odd4 frame = new Odd4();
frame.setSize(100, 100);
frame.createLine();
frame.show();
}
private void createLine() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container window=getContentPane();
window.setLayout (new FlowLayout());
button = new JButton("OK");
window.add(button);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent event) {
int n;
int sum = 0;
int i;
int s = 1;
String nString;
nString = JOptionPane.showInputDialog("n:");
n = Integer.parseInt(nString);
for (i = 1; i <= n; i ++){
if (i%2 == 0)
do {
j=j+i;
sum = sum + j;
}
while (j <= n);
}
JOptionPane.showMessageDialog(null, "Total is: " + sum);
}

Pretty sure you want something like this:
public static void main(final String[] args) {
long total = 1;
for( int i = 0; i < 10; i++ ) {
total += (2*i);
System.out.println(total);
}
}
In my test it prints out:
1
3
7
13
21
31
43
57
73
91
EDIT: solution to add the terms up
public static void main(final String[] args) {
long total = 0;
long term = 1;
for( int i = 0; i < 5; i++ ) {
term += (2*i);
total += term;
System.out.println("Term " + i + " is " + term);
System.out.println("Current Total is " + total);
}
}
Term 0 is 1
Current Total is 1
Term 1 is 3
Current Total is 4
Term 2 is 7
Current Total is 11
Term 3 is 13
Current Total is 24
Term 4 is 21
Current Total is 45
EDIT: Added complete solution on Ideone
As per the request fo the OP in the comments, I threw together a complete solution in Ideone. It's here!

will this help?
int a[];
int i=0,f=1,a=2.sum=0;
while(f<=n)
{
a[i]=f;
f=f+a;
a=a+2;
i++;
}
for(int j=0;j<a.length;j++)
{
sum+=a[j];
}

You don't actually need a loop to solve this.
Each term is 1 plus the sum of even number e.g. 1, 1 + 2, 1 + 2 + 4, 1 + 2 + 4 + 6.
The sum of even numbers is x*(x+1) and plus 1 makes n^2 + n + 1.
Then you want to sum these terms.
The sum of squares is n*(n+1)*(2*n+1)/6
The sum of numbers is n*(n+1)/2
The sum of 1, (n+1) times is n+1
The solution is
n*(n+1)*(2*n+1)/6 + n*(n+1)/2 + n + 1
or
(2*n^3 + 7*n^2 + 10*n + 6)/6
e.g
1 + 3 + 7 + 13 + 21 = 45
21 is the 4th term so
(2*4^3 + 7*4^2 + 10*4 + 6)/6 = 45
Using the formula and looking at the differences, and differences of differences
term sum value even
0 1 1
1 4 3 2
2 11 7 4 2
3 24 13 6 2
4 45 21 8 2
5 76 31 10 2
6 119 43 12 2
7 176 57 14 2
8 249 73 16 2
9 340 91 18 2
10 451 111 20 2

And even number can be written 2i and an odd number 2i+1.
So i am not sure about your problem but for doing the sum you make a loop increasing i and sum until your number reach n :
Edit : correct (sum start to 1 and add even):
i = 0;
sum = 1;
while (2*i <= n){ // or 2*i +1 for odd
sum += 2*i;
i++;
}
Edit2: the correct answer
public class HelloWorld{
public static void main(String []args){
int i=0;
int n=7;
int sum=1;
int total = 0;
while (sum < n){ // or 2*i +1 for odd
sum += 2*i;
total += sum;
i++;
}
System.out.println(total);
}
}

This is what you want I think:-
sumofEven will give you the sum of numbers at even places.
public class Sample {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
long n =21 ;
int i= 0;
long sumofEven =0;
long sumofAll =1;
while(sumofAll <= n){
sumofAll = (long) (sumofAll + 2*i);
System.out.println("->"+sumofAll);
if((i+1) % 2 == 0){
sumofEven = sumofEven + sumofAll;
}
i++;
}
System.out.println("sumofAll Numbers : "+sumofAll +"\nSum of no at event place : "+sumofEven);
}
}

Terms can be written like that :
...
So you need to sum these terms while they are less than user input n:
int i=0, n = userInput, term;
int sum=0;
while((term = (i*(i+1)+1)) < n) {
sum+=term;
i++;
}
You can see it working in this ideone

Related

How do I make it so the last multiplication sign is not included in the line of factorials?

So I need to get rid of this final multiplication sign in each line. I've tried a few different ways but they just messed up my code or didn't work, and I can't seem to wrap my head around how to go about this.
Here's an example of the output:
Starting value (at least 2):
59
Ending value (at least 2):
64
59 = 59 x
60 = 2 x 2 x 3 x 5 x
61 = 61 x
62 = 2 x 31 x
63 = 3 x 3 x 7 x
64 = 2 x 2 x 2 x 2 x 2 x 2 x
Here's how I want it to look:
Starting value (at least 2):
59
Ending value (at least 2):
64
59 = 59
60 = 2 x 2 x 3 x 5
61 = 61
62 = 2 x 31
63 = 3 x 3 x 7
64 = 2 x 2 x 2 x 2 x 2 x 2
And here's the code:
import java.util.Scanner;
public class PrimeFact {
public static void main(String[] args) {
int start, stop;
int number = 0;
Scanner input = new Scanner(System.in);
System.out.println("Starting value (at least 2): ");
start = input.nextInt();
System.out.println("Ending value (at least 2): ");
stop = input.nextInt();
// stops the program if the user entered n input that cannot be factored
if (start < 2 || stop < 2) {
System.out.println("Amount must be at least 2 rather than " + start + " and " + stop + ". Quitting.");
System.exit(0);
} // end if
// loop
// calls factors
for (int i = start; i <= stop; i++) {
number = i;
printFactors(i);
System.out.println();
} // ends loop
}// ends main
// prints prime factors
public static void printFactors(int number) {
int out = number;
int count = 0;
System.out.print(out + " = ");
for (int factor = 2; factor <= number; factor++) {
int exponent = 0;
while (number % factor == 0) {
number /= factor;
exponent++;
count++;
}
if (exponent > 0) {
printExponents(exponent, factor, count);
}
}
}
//prints the factors the required number of times
public static void printExponents(int exponent, int factor, int count) {
for (int q = 1; q <= exponent; q++) {
System.out.print(factor + " x ");
// if (q /= count) {
// System.out.print(factor);
// }
}
}
}// ends class
into printFactors near the declarations of the ints add in
boolean hadFactor = false;
also amend your call there to:
if (exponent > 0) {
printExponents(exponent, factor, count, hadFactor);
hadFactor=true;
}
and in printExponents do
public static void printExponents(int exponent, int factor, int count, boolean hadFactor) {
for (int q = 1; q <= exponent; q++) {
if (hadFactor){System.out.print(" x ")}
System.out.print(factor);
hadFactor=true;
// if (q /= count) {
// System.out.print(factor);
// }
}

Is there something wrong with my id array?

This program pulls two columns from the input.txt file where the first column indicates the value of the object, and the second column represents the weight. The values are imported and placed into two arrays: the value array and the weight array. The knapsack calculations are then made. There are 23 objects in total represented by the rows of the arrays. My code correctly calculates the total value that is being held in the knapsack, and will print out the correct IDs if the weight capacity entered is 5, but for any other weight the IDs being held in the id array are not correct, but the total value printed out is. Here is my code for both files, and if anyone is able to figure out how to correctly save and print the IDs being held in the knapsack please let me know . . .
input.txt file:
17 5
12 8
15 22
17 11
33 21
43 15
15 4
44 35
23 19
10 23
55 39
8 6
21 9
20 28
20 13
45 29
18 16
21 19
68 55
10 16
33 54
3 1
5 9
knapsack.java file:
//We did borrow concepts from:
//http://www.sanfoundry.com/java-program-solve-knapsack-problem-using-dp/
import java.util.Scanner;
import java.util.*;
import java.lang.*;
import java.io.*;
public class knapsack
{
static int max(int a, int b)
{
if(a > b)
{
//System.out.println(a);
return a;
}
else
//System.out.println(b);
return b;
}
static int knapSack(int maxCapacity, int weight[], int value[], int n)
{
int track = 0;
int i, w;
int foo1 = 0;
int foo2 = 0;
K = new int[n+1][maxCapacity+1];
// Build table K[][] in bottom up manner
for (i = 0; i <= n; i++)
{
for (w = 0; w <= maxCapacity; w++)
{
if (i==0 || w==0)
K[i][w] = 0;
else if (weight[i-1] <= w)
{
//K[i][w] = max(value[i-1] + K[i-1][w-weight[i-1]], K[i-1][w]);
if(value[i-1] + K[i-1][w-weight[i-1]] > K[i-1][w])
{
K[i][w] = value[i-1] + K[i-1][w-weight[i-1]];
//System.out.println("A: "+i);
}
else
{
K[i][w] = K[i-1][w];
id[track++] = i;
//System.out.println("B: "+i);
}
}
else
{
K[i][w] = K[i-1][w];
}
}
//System.out.println(K[foo1][foo2]);
}
return K[n][maxCapacity];
}
public static void main(String args[])throws java.io.FileNotFoundException
{
Scanner sc = new Scanner(System.in);
int n = 23;
File file = new File("input.txt");
Scanner scanner = new Scanner(file);
id = new Integer [n];
//knapval = new int[n];
//knapweight = new int [n];
int []value = new int[n];
int []weight = new int[n];
for(int i=0; i<n; i++)
{
value[i] = scanner.nextInt();
weight[i] = scanner.nextInt();
}
System.out.println("Enter the maximum capacity: ");
int maxCapacity = sc.nextInt();
System.out.println("The maximum value that can be put in a knapsack with a weight capacity of "+maxCapacity+" is: " + knapSack(maxCapacity, weight, value, n));
System.out.println();
System.out.println("IDs Of Objects Held In Knapsack: ");
//System.out.println();
for(int z = 0; z < n && id[z] != null; z++)
{
System.out.println(id[z]);
}
if(id[0] == null)
System.out.println("All objects are too heavy, knapsack is empty.");
sc.close();
scanner.close();
}
protected static Integer [] id;
protected static int [][]K;
}
Your way of recording your solution in the id array is flawed. At the time you do id[track++] = i;, you don’t yet know whether i will be in your final solution. Because of the nested loops you may even add i more than once. This in turn may lead to overflowing the array with a java.lang.ArrayIndexOutOfBoundsException: 23 (this happens for max capacity 12 and above).
I suggest instead of using id, after your solution is complete you track your way backward through the K array (by Java naming conventions, it should be a small k). It holds all the information you need to find out which objects were included in the maximum value.
private static void printKnapsack(int maxCapacity, int weight[], int value[], int n) {
if (K[n][maxCapacity] == 0) {
System.out.println("No objects in knapsack");
} else {
int w = maxCapacity;
for (int i = n; i > 0; i--) {
if (K[i][w] > K[i - 1][w]) { // increased value from object i - 1
System.out.format("ID %2d value %2d weight %2d%n", i, value[i - 1], weight[i - 1]);
// check that value in K agrees with value[i - 1]
assert K[i - 1][w - weight[i - 1]] + value[i - 1] == K[i][w];
w -= weight[i - 1];
}
}
}
}
The above prints the objects backward. Example run:
Enter the maximum capacity:
13
The maximum value that can be put in a knapsack with a weight capacity of 13 is: 36
ID 13 value 21 weight 9
ID 7 value 15 weight 4
If you want the objects in forward order, inside the for loop put them into a list (you may for instance use id from your old attempt), and then print the items from the list in opposite order.

Finding Multiples of a number between a range [Java]

We have been given a range A<=B and a number M. We have to find how many multiples of M lie in the given range.
My Solution:
import java.util.Scanner;
class ABC {
public static void main(String args[] ) throws Exception {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
for (int i = 0; i < N; i++) {
long A = sc.nextLong();
long B = sc.nextLong();
long M = sc.nextLong();
int res = 0;
while(A<=B)
{
if(A%M==0)res++;
A++;
}
System.out.println(res+"");
}
}
}
Now this is not very efficient. Please tell me how this problem can be solved in least amount of time.
The smallest integer n1 such that n1*M ≥ A is n1=ceil(A/M), and the largest integer n2 such that n2*M ≤ B is n2=floor(B/M). The number of integers between n1 and n2 inclusive is max_of(n2−n1+1 ; 0).
Combining the above we have the answer:
max_of(floor(Z/X)−ceil(Y/X)+1 ; 0)
This is a somewhat standard problem in competitive programming :D
Following should do it (after some more testing).
int r = (b/m - a/m) + (a % m == 0 ? 1 : 0);
explanation
find the amount of multiples m between a/m and b/m
if a is a multiple of m add one more (a % m == 0 ? 1 : 0)
small example PoC
public static void main(String[] args) throws Exception {
int[][] pairs = {{10, 24}, {10, 25}, {11, 24}, {11, 25}, {10, 27}};
int m = 5;
for (int[] pair : pairs) {
int a = pair[0];
int b = pair[1];
int r = (b/m - a/m) + (a % m == 0 ? 1 : 0);
System.out.printf("a: %d b: %d result = %d ", a, b, r);
for (int i = a; i <= b; i++) {
if (i % m == 0) {
System.out.print(" " + i);
}
}
System.out.println("");
}
}
output
a: 10 b: 24 result = 3 10 15 20
a: 10 b: 25 result = 4 10 15 20 25
a: 11 b: 24 result = 2 15 20
a: 11 b: 25 result = 3 15 20 25
a: 10 b: 27 result = 4 10 15 20 25
Try this code :
long A = sc.nextLong();
long B = sc.nextLong();
long M = sc.nextLong();
if (M > A) {
A = M;
}
if(M > B){
System.out.println("0");
return;
}
System.out.println( (((B-A)/M)+1) + "");
Explanation :
if 2 is first multiple than we dont need to check for 3, we have to add 2 to get next multiple so we dont need to traverse from first value to last and check if value is multiple or not, we just need to find first multiple and than number of steps it will take to reach last number means our B by adding M to A.
This works great.
int multiples = 0;
for(int i = x; i<=y; i++){
if(i%z==0)
multiples++;
}
As long as y>x, if that isn't always true just add an additional if statement that checks if y>x or x>y. :)

Project-Euler -- Problem20

I thought I solved this problem but the program output "0". I don't see any problem. Thank you for helping.
Question :
n! means n × (n − 1) × ... × 3 × 2 × 1
For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum of
the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
Find the sum of the digits in the number 100!
package projecteuler;
public class problem20 {
public static void main(String[] args)
{
int sayi=0;
int carpim=1;
for(int i=100;i>=1;i--)
{
carpim*=i;
}
String carp=""+carpim;
int[] dizi = new int[carp.length()];
String[] dizis=new String[carp.length()];
for(int i=0;i<carp.length();i++)
{
dizis[i]=carp.substring(i);
}
for(int i=0;i<carp.length();i++)
{
dizi[i]=Integer.parseInt(dizis[i]);
sayi+=dizi[i];
}
System.out.println(sayi);
}
}
100! is 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
, and that exceeds the valid range of an int (by rather a lot). Try using a BigInteger. To get you started,
BigInteger carpim = BigInteger.ONE;
for (int i = 100; i >= 1; i--) {
carpim = carpim.multiply(BigInteger.valueOf(i));
}
System.out.println(carpim);
The output of which is the number mentioned before.
It appears the number is overflowing. https://ideone.com/UkXQ4e
4611686018427387904
-4611686018427387904
-9223372036854775808
-9223372036854775808
0
0
0
You might want to try a different class for the factorial like BigInteger
In college, I got this example for finding n! using this algorithm. this is based on the fact that n! = n * (n-1)! (for example, 5! = 4 * 3!). Using a recursive algorithm:
function factorial(n)
if (n = 0) return 1
while (n != 0)
return n * [factorial(n-1)]
once you have 100!, its easy to parse it as String and make Integers out of it to get the sum
int sum = 0;
for (Character c : yourBigInteger.toString().toCharArray()) {
sum = sum + Integer.parseInt(c.toString());
}
System.out.println(sum);
public static void descomposicionFactorial(int num) {
BigInteger factorial = BigInteger.ONE;
for (int i = num; i > 0; i--) {
factorial = factorial.multiply(BigInteger.valueOf(i));
}
String aux =factorial.toString();
char cantidad[] = aux.toCharArray();
int suma = 0, numero = 0;
for (int i = 0; i <cantidad.length; i++) {
numero = cantidad[i] - '0';
suma += numero;
}
System.out.println(suma);
}

How to find a duplicate of length 5 in a single array. Java

I create an array that then prints in sets of five. I want to then be able to search the array by 5 to see if there are any duplicates. I've tried but I can only think of a way to search by each value not five. If anyone can point me in the right direction, that would be great. Thanks.
public class findPat {
static int arr [] = new int [10];
static int st = 1;
static int end = 56;
static double t1;
static double t2;
public static void main(String[] args){
t1=System.currentTimeMillis();
for(int n=0; n<100; n++){
for (int i=0; i<arr.length; i++)
arr[i]= (int) (Math.random()* (end-st +1)) +st;
for (int i=0; i<5; i++){
if (i%5==0)
System.out.println();
System.out.print("\t" + arr[i]);}
}
t2=System.currentTimeMillis();
System.out.println();
System.out.println();
System.out.println("\t" + "Total run time is " + ((t2-t1)) + "ms");
}
}
the console looks like this:
18 22 42 14 38
2 2 14 9 8
6 29 38 37 33
6 41 41 27 7
20 41 38 11 50
16 17 41 21 19
40 33 9 10 7
12 54 10 30 36
however each row is in the same array but is just printing 5 at a time.
the console will have more than just those few lines. I want to be able to search the array and check each row against the rest to see how many times it appears, if it does.
You could implement this using a Hashtable. Using your code as a base, I've written an example implementation but without knowing what it is you are trying to do, I can't judge if this is what you are looking for.
import java.util.Hashtable;
public class findPat {
static final int COUNT = 100;
static Hashtable<String, Integer> compareSet = new Hashtable<String, Integer>();
static String groupInteger = "";
static int arr [] = new int [5];
static int st = 1;
static int end = 56;
static double t1;
static double t2;
public static void main(String[] args) {
t1=System.currentTimeMillis();
for(int n = 0; n < COUNT; n++){
for (int i = 0; i < arr.length; i++) {
arr[i] = (int) (Math.random()* (end - st + 1)) + st;
}
for (int i = 1; i <= 5; i++) {
groupInteger += arr[i-1];
System.out.print("\t" + arr[i-1]);
if (i % 5 == 0) {
System.out.println();
if (compareSet.containsKey(groupInteger)) {
System.out.println("duplicate found");
int currentCount = compareSet.get(groupInteger);
compareSet.put(groupInteger, currentCount + 1);
} else {
compareSet.put(groupInteger, 1);
}
groupInteger = "";
}
}
}
t2=System.currentTimeMillis();
System.out.println();
System.out.println();
System.out.println("\t" + "Total run time is " + ((t2 - t1)) + "ms");
}
}
This code keeps track of the unique sets of random numbers by adding them (creating a key value that is the same for every set that has the same values in the same order, the concatenated string takes care of this).
Your code ran in 13 seconds on my system, mine takes 17 seconds. Now if runtime is of crucial importance, you might want to look into hashing techniques. But I'm not sure if you will be able to shave off a lot as you will have to add some extra code which will take extra time.

Categories