i'm trying to write a program in java to print a list of arrays. I know there's already Array.toString(arr) method, but i don't want the "[..]" on the list. I wrote some simple code to do so.
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int t = in.nextInt();
int[] v = new int[10000];
for(int i = 0; i <= t; i++){
int m = in.nextInt();
int n = in.nextInt();
int list = 0;
for(int min = m; min < n; min++){
if(isPrime(min) == true){
v[list] = min;
list++;
}
}
System.out.printf(("%d \n"), list + ("\n \n"));
}
}
public static boolean isPrime(int num){
int sqrt = (int) Math.sqrt(num) + 1;
for(int i = 2; i < sqrt; i++){
if(num % i == 0)
return false;
}
return true;
}
Say that this is the Input
1
1 10
and the Output is
2
3
5
7
in this exact order and formatting.
What am i doing wrong?
this will solve your error
System.out.printf(("%d \n"), list,( "\n \n"));
But if you want to print prime numbers then you need to print num instead of list
for(int min = m; min < n; min++){
if(isPrime(min) == true){
v[list] = min;
list++;
System.out.printf(("%d \n"), min,( "\n \n"));
}
}
}
Related
I have an array with several numbers:
int[] tab = {1,2,3,4};
I have to create two methods the first is the sum() method and the second is numberOdd().
It's Ok for this step !
int length = tab.length;
length = numberOdd(tab,length);
int sum_odd = sum(tab, length);
System.out.println(" 1) - Calculate the sum of the odds numbers : => " + sum_odd);
public static int sum(int[] tab, int length){
int total = 0;
for(int i=0;i<length;i++){
total += tab[i];
}
return total;
}
public static int numberOdd(int[] tab, int length){
int n = 0;
for(int i=0;i<length;i++){
if(tab[i] % 2 != 0){
tab[n++] = tab[i];
}
}
return n;
}
Now, I have to add the even numbers with the numberEven() method and I get the value "0".
I don't understand why I retrieve the value => 0 ???????
Here is my code:
int[] tab = {1,2,3,4};
int length = tab.length;
length = numberOdd(tab,length);
int sum_odd = sum(tab, length);
length = numberEven(tab,length);
int sum_even = sum(tab, length);
System.out.println(" 1) - Calculate the sum of the odds numbers : => " + sum_odd);
System.out.println(" 2) - Calculate the sum of the evens numbers : => " + sum_even);
}
public static int numberEven(int[] tab, int length){
int n = 0;
for(int i=0;i<length;i++){
if(tab[i] % 2 == 0){
tab[n++] = tab[i];
}
}
return n;
}
For information: I share the code here => https://repl.it/repls/CriminalAdolescentKilobyte
Thank you for your help.
You need to add tab[i] to n
Having length as a parameter to numberEven does not cause any harm but you don't need it.
Given below is the working example:
public class Main {
public static void main(String[] args) {
int[] tab = { 1, 2, 3, 4 };
System.out.println(numberEven(tab));
}
public static int numberEven(int[] tab) {
int n = 0;
for (int i = 0; i < tab.length; i++) {
if (tab[i] % 2 == 0) {
n += tab[i];
}
}
return n;
}
}
Output:
6
you have changed the array in your numberOdd() method.
try replacing tab[n++] = tab[i]; with n++;
public static int sumEven(int[] tab){
int sumEven = 0;
for(int i=0;i<tab.length;i++){
if(tab[i] % 2 == 0){
sumEven = sumEven + tab[i];
}
}
return sumEven;
}
This should work.
First of all let me say I am quite new to programming its been my second week since I started so if you see any bad practice or error in code please accept my apologies.
I want to print sum of first n odd numbers. But so far I can only do the sum of odd number up to the given number. kindly help.
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);
System.out.print("Please enter the number : ");
int num1 = userInput.nextInt();
int sum = sumOfOdd(num1);
System.out.println("sum of first " +num1 + " odd numbers is " + sum);
userInput.close();
}
static int sumOfOdd(int num)
{
int sum = 0;
for (int i = 0; i <= num; i++)
{
if(i % 2 != 0)
{
sum += i;
}
}
return sum;
}
}
You don't have to use a loop at all
static int sumOfOdd(int num) {
return num*num;
}
For Any Arithmetic Progression, the sum of numbers is given by,
Sn=1/2×n[2a+(n-1)×d]
Where,
Sn= Sum of n numbers
n = n numbers
a = First term of an A.P
d= Common difference in an A.P
Using above formula we can derive this quick formula to calculate sum of first n odd numbers,
Sn(odd numbers)= n²
Try this it uses a for loop that increments by two to only account for odd numbers.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the value of n: ");
int n = scanner.nextInt();
System.out.println("The sum of the first " + n + " odd numbers is: " + sumOfOddNumbers(n));
}
public static int sumOfOddNumbers(int n) {
int sum = 0;
for(int i = 1; i < n*2; i+=2) {
sum += i;
}
return sum;
}
}
Example usage:
Enter the value of n: 5
The sum of the first 5 odd numbers is: 25
Try this:
static int sumOfOdd(int num) {
int sum = 0;
for (int i = 0; i < num; i++){
sum += i*2+1;
}
return sum;
}
It sums up all odd numbers until the limit is reached.
With i*2+1 you get the next odd number. Then you add it to the sum.
Tested with System.out.println(sumOfOdd(4)); and got the expected result 16 (1+3+5+7)
Change the counter to the number of times you add an odd number to the sum value...
static int sumOfOdd(int num) {
int sum = 0;
int i = 0;
int count = 0;
do {
if(i % 2 != 0) {
sum += i;
count++;
}
i++;
} while (count < num);
return sum;
}
Or even cleaner:
static int sumOfOdd(int num) {
int sum=0;
for (int i=1;i<num*2;i+=2) {
sum=sum+i;
}
return sum;
}
You should count how many numbers have you added and in the condition to check if count of numbers you summed is less or equal than your n. Just add the counter in your for loop and set condition to: count <= num and it should work.
Every time you add a number to the sum increment the count by count++.
The code suppose to look like this:
static int sumOfOdd(int num)
{
int sum = 0;
int count = 0;
for (int i = 0, count= 0; count <= num; i++)
{
if(i % 2 != 0)
{
sum += i;
count++;
}
}
return sum;
}
I haven't checked it, but it should be correct
Since you don't know how many loop cycles are required you have to change the exit condition of the for loop.
Or you can use a while loop exploiting the same exit condition.
static int sumOfOdd(int num){
int sum = 0;
int counter = 0;
int currentNumber = 0;
while (counter<num){
if(currentNumber % 2 != 0){
sum += currentNumber;
counter++;
}
currentNumber++;
}
return sum;
}
Here is the complete code you'd be using:
public class YourClass {
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);
System.out.print("Please enter the number : ");
int num1 = userInput.nextInt();
int sum = sumOfOdd(num1);
System.out.println("sum of first " +num1 + " odd numbers is " + sum);
userInput.close();
}
static int sumOfOdd(int num)
{
int counter = 0;
for (int i = 0;; i++)
{
int sum = 0;
if(i % 2 != 0)
{
counter++;
sum += i;
}
if(counter == num) return sum;
}
}
}
Another alternative.
static int sumOfOdd(int num) {
int sum = 0;
int last = 2*num-1;
for (int i = 1; i <= last; i+=2){
sum += i;
}
return sum;
}
Obviously return num*num; is the most efficient but if you're obliged to use a loop then this method avoids a * inside the loop.
This will be a tiny (tiny) bit more efficient than:
for (int i = 0; i < num; ++i){
sum += 2*i+1;
}
import java.util.*;
class karan{
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int i = n;
int sumOddNumber = n * i;
System.out.println(n*i);
}
}
The program I have currently takes N numbers and then a goal target. It inserts either "+" or "*" in between the numbers to try reach the goal. If it can reach the goal it will print out the correct operations.
However the way it finds the answer is by brute force, which is inadequate for a large set of N numbers. My current code is below:
public class Arithmetic4{
private static ArrayList<String> input = new ArrayList<String>();
private static ArrayList<String> second_line = new ArrayList<String>();
private static ArrayList<Integer> numbers = new ArrayList<Integer>();
private static ArrayList<String> operations = new ArrayList<String>();
private static ArrayList<Integer> temp_array = new ArrayList<Integer>();
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine()){
readInput(sc);
}
}
public static void readInput(Scanner sc){
String line = sc.nextLine();
input.add(line);
line = sc.nextLine();
second_line.add(line);
dealInput();
}
public static void dealInput(){
String numberS = input.get(0);
String[] stringNumbers = numberS.split("\\s+");
for(int i = 0; i < stringNumbers.length; i++){
String numberAsString = stringNumbers[i];
numbers.add(Integer.parseInt(numberAsString));
}
String orderString = second_line.get(0);
String[] stringWhatWay = orderString.split("\\s+");
int target = Integer.parseInt(stringWhatWay[0]);
char whatway = stringWhatWay[1].charAt(0);
long startTime = System.currentTimeMillis();
whatEquation(numbers, target, whatway);
long elapsedTime = System.currentTimeMillis() - startTime;
long elapsedMSeconds = elapsedTime / 1;
System.out.println(elapsedMSeconds);
numbers.clear();
input.clear();
second_line.clear();
}
public static void whatEquation(ArrayList<Integer> numbers, int target, char whatway){
if(whatway != 'L' && whatway != 'N'){
System.out.println("Not an option");
}
if(whatway == 'N'){
ArrayList<Integer> tempo_array = new ArrayList<Integer>(numbers);
int count = 0;
for (int y: numbers) {
count++;
}
count--;
int q = count;
calculateN(numbers, target, tempo_array, q);
}
if (whatway == 'L'){
if(numbers.size() == 1){
System.out.println("L " + numbers.get(0));
}
ArrayList<Integer> temp_array = new ArrayList<Integer>(numbers);
calculateL(numbers, target, temp_array);
}
}
public static void calculateN(ArrayList<Integer> numbers, int target, ArrayList<Integer> tempo_numbers, int q){
int sum = 0;
int value_inc = 0;
int value_add;
boolean firstRun = true;
ArrayList<Character> ops = new ArrayList<Character>();
ops.add('+');
ops.add('*');
for(int i = 0; i < Math.pow(2, q); i++){
String bin = Integer.toBinaryString(i);
while(bin.length() < q)
bin = "0" + bin;
char[] chars = bin.toCharArray();
List<Character> oList = new ArrayList<Character> ();
for(char c: chars){
oList.add(c);
}
ArrayList<Character> op_array = new ArrayList<Character>();
ArrayList<Character> temp_op_array = new ArrayList<Character>();
for (int j = 0; j < oList.size(); j++) {
if (oList.get(j) == '0') {
op_array.add(j, ops.get(0));
temp_op_array.add(j, ops.get(0));
} else if (oList.get(j) == '1') {
op_array.add(j, ops.get(1));
temp_op_array.add(j, ops.get(1));
}
}
sum = 0;
for(int p = 0; p < op_array.size(); p++){
if(op_array.get(p) == '*'){
int multiSum = numbers.get(p) * numbers.get(p+1);
numbers.remove(p);
numbers.remove(p);
numbers.add(p, multiSum);
op_array.remove(p);
p -= 1;
}
}
for(Integer n: numbers){
sum += n;
}
if(sum != target){
numbers.clear();
for (int t = 0; t < tempo_numbers.size(); t++) {
numbers.add(t, tempo_numbers.get(t));
}
}
if (sum == target){
int count_print_symbol = 0;
System.out.print("N ");
for(int g = 0; g < tempo_numbers.size(); g++){
System.out.print(tempo_numbers.get(g) + " ");
if(count_print_symbol == q){
break;
}
System.out.print(temp_op_array.get(count_print_symbol) + " ");
count_print_symbol++;
}
System.out.print("\n");
return;
}
}
System.out.println("N is Impossible");
}
public static void calculateL(ArrayList<Integer> numbers, int target, ArrayList<Integer> temp_array){
int op_count = 0;
int sum = 0;
int n = (numbers.size() -1);
boolean firstRun = true;
for (int i = 0; i < Math.pow(2, n); i++) {
String bin = Integer.toBinaryString(i);
while (bin.length() < n)
bin = "0" + bin;
char[] chars = bin.toCharArray();
char[] charArray = new char[n];
for (int j = 0; j < chars.length; j++) {
charArray[j] = chars[j] == '0' ? '+' : '*';
}
//System.out.println(charArray);
for(char c : charArray){
op_count++;
if(firstRun == true){
sum = numbers.get(0);
numbers.remove(0);
// System.out.println(sum);
}
if (!numbers.isEmpty()){
if (c == '+') {
sum += numbers.get(0);
} else if (c == '*') {
sum *= numbers.get(0);
}
numbers.remove(0);
}
firstRun = false;
//System.out.println(sum);
if(sum == target && op_count == n){
int count_print_op = 0;
System.out.print("L ");
for(int r = 0; r < temp_array.size(); r++){
System.out.print(temp_array.get(r) + " ");
if(count_print_op == n){
break;
}
System.out.print(charArray[count_print_op] + " ");
count_print_op++;
}
System.out.print("\n");
return;
}
if(op_count == n && sum != target){
firstRun = true;
sum = 0;
op_count = 0;
for(int e = 0; e < temp_array.size(); e++){
numbers.add(e, temp_array.get(e));
}
}
}
}
System.out.println("L is impossible");
}
}
Is there a faster to way to reach a similar conclusion?
This problem can be solved in O(NK²) using the Dynamic Programming paradigm, where K is the maximum possible value for the goal target. This is not that good and maybe there is a faster algorithm, but it's still a lot better than the O(2^N) brute force solution.
First let's define a recurrence to solve the problem: let G be the goal value and f(i,j,k) be a function that returns:
1 if we can reach the value G-j-k using only elements from index i and onwards
0 otherwise
We are going to use j as an accumulator that holds the current total sum and k as an accumulator that holds the total product of the current chain of multiplications, you will understand it soon.
The base cases for the recurrence are:
f(N,x,y) = 1 if x+y = G (we have used every element and reached our goal)
f(N,x,y) = 0 otherwise
f(i,x,y) = 0 i != N and x+y >= G (we have exceeded the goal before using every element)
For other i values we can define the recurrence as:
f(i,j,k) = max( f(i+1,j+k,v[i]) , f(i+1,j,k*v[i]) )
The first function call inside max() means that we will put a "+" sign before the current index, so our current multiplication chain is broken and we have to add its total product to the current sum, so the second parameter is j+k, and since we are starting a new multiplication chain right now, it's total product is exactly v[i].
The second function call inside max() means that we will put a "*" sign before the current index, so our current multiplication chain is still going on, so the second parameter remains j, and the third parameter will become k * v[i].
What we want is the value of f(0,0,0) (we haven't used any elements, and our current accumulated sums are equal to 0). f(0,0,0) equals 1 if and only if there is a solution for the problem, so the problem is solved. Now let's go back to the recurrence and fix a detail: when we run f(0,0,0), the value of k*v[i] will be 0 no matter the value of v[i], so we have to add a special check when we are computing the answer for i = 0, and the final recurrence will look like this:
f(i,j,k) = max( f(i+1,j+k,v[i]) , f(i+1,j,(i==0?v[i]:k*v[i])) )
Finally, we apply the memoization/dynamic programming paradigm to optimize the calculation of the recurrence. During the execution of the algorithm, we will keep track of every calculated state so when this state is called again by another recursive call we just return the stored value instead of computing its whole recursion tree again. Don't forget to do this or your solution is going to be as slow as a brute force solution (or even worse) due to recalculation of subproblems. If you need some resources on DP, you can start here: https://en.wikipedia.org/wiki/Dynamic_programming
I was practicing with some exercises from UVA Online Judge, I tried to do the Odd sum which basically is given a range[a,b], calcule the sum of all odd numbers from a to b.
I wrote the code but for some reason I don't understand I'm getting 891896832 as result when the range is [1,2] and based on the algorithm it should be 1, isn't it?
import java.util.Scanner;
public class OddSum
{
static Scanner teclado = new Scanner(System.in);
public static void main(String[] args)
{
int T = teclado.nextInt();
int[] array = new int[T];
for(int i = 0; i < array.length; i++)
{
System.out.println("Case "+(i+1)+": "+sum());
}
}
public static int sum()
{
int a=teclado.nextInt();
int b = teclado.nextInt();
int array[] = new int[1000000];
for (int i = 0; i < array.length; i++)
{
if(a%2!=0)
{
array[i]=a;
if(array[i]==(b))
{
break;
}
}
a++;
}
int res=0;
for (int i = 0; i < array.length; i++)
{
if(array[i]==1 && array[2]==0)
{
return 1;
}
else
{
res = res + array[i];
}
}
return res;
}
}
Your stopping condition is only ever checked when your interval's high end is odd.
Move
if (array[i] == (b)) {
break;
}
out of the if(a % 2 != 0) clause.
In general, I don't think you need an array, just sum the odd values in your loop instead of adding them to the array.
Keep it as simple as possible by simply keeping track of the sum along the way, as opposed to storing anything in an array. Use a for-loop and add the index to the sum if the index is an odd number:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter minimum range value: ");
int min = keyboard.nextInt();
System.out.println("Enter maximum range value: ");
int max = keyboard.nextInt();
int sum = 0;
for(int i = min; i < max; i++) {
if(i % 2 != 0) {
sum += i;
}
}
System.out.println("The sum of the odd numbers from " + min + " to " + max + " are " + sum);
}
I don't have Java installed right now, however a simple C# equivalent is as follows: (assign any values in a and b)
int a = 0;
int b = 10;
int result = 0;
for (int counter = a; counter <= b; counter++)
{
if ((counter % 2) != 0) // is odd
{
result += counter;
}
}
System.out.println("Sum: " + result);
No major dramas, simple n clean.
Problem H [Longest Natural Successors]
Two consecutive integers are natural successors if the second is the successor of the first in the sequence of natural numbers (1 and 2 are natural successors). Write a program that reads a number N followed by N integers, and then prints the length of the longest sequence of consecutive natural successors. Example:
Input
7 2 3 5 6 7 9 10 Output 3
here is my code so far can anyone help me plz
import java.util.Scanner;
public class Conse {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int x=scan.nextInt();
int[] array= new int[x];
for(int i=0;i<array.length;i++)
array[i]=scan.nextInt();
System.out.println(array(array));
}
public static int array(int[] array){
int count=0,temp=0;
for(int i=0;i<array.length;i++){
count=0;
for(int j=i,k=i+1;j<array.length-1;j++,k++)
if(array[j]-array[k]==1)
count++;
else{if(temp<count)
temp=count;
break;}
}
return temp+1;
}
}
Try this
ArrayList<Integer> outList = new ArrayList<Integer>()
int lastNum = array[0];
for(int i = 1; i < array.length; i++;)
if((lastNum + 1) == array[i])
outList.add(array[i]);
I think the line i=counter; should be i += counter. otherwise, you're always resetting the loop-counter i to zero, and so it never progresses.
You don't need the inner for loop, as this can be done with one single scan through the array:
public static int consecutive(int[]array) {
int tempCounter = 1; //there will always be a count of one
int longestCounter = 1; //always be a count of one
int prevCell = array[0];
for(int i=1;i<array.length;i++) {
if( array[i] == (prevCell + 1)) {
tempCounter++; //consecutive count increases
} else {
tempCount =1; //reset to 1
}
if(tempCounter > longestCounter) {
longestCounter = tempCounter; //update longest Counter
}
prevCell = array[i];
}
return longestCounter;
}
int sequenceStart = 0;
int sequenceLength = 0;
int longestSequenceLength = 0;
for (int item: array) {
if (item == sequenceStart + sequenceLength) {
sequenceLength++;
} else {
sequenceStart = item;
sequenceLength = 1;
}
longestSequenceLength = Math.max(longestSequenceLength, sequenceLength);
}