I have tried programming recently and there is an exercise online that involves adding the odd integer values of any inputted integer.
My code is able to output the sum of the odd integer values but the exercise asks to output an addition sequence like 1 + 3 + 5... = sum.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int number, oddSumPositive = 0, oddSumNegative = 0;
System.out.print("Enter an integer : ");
number = input.nextInt();
oddSumPositive = sumOfOdd_Postive(number);
oddSumNegative = sumOfOdd_Negative(number);
//different scenarios
if(number > 0) {
System.out.println("\nThe Sum of Odd Numbers upto " + number + " = " + oddSumPositive);
}
else if(number < 0) {
System.out.println("\nThe Sum of Odd Numbers upto " + number + " = " + oddSumNegative);
}
else if(number == 0) {
System.out.println("\nThe Sum of Odd Numbers upto 0 = 0");
}
else {
System.out.println("\nError");
}
}
//Method for positive integers
public static int sumOfOdd_Postive(int num)
{
int i, sum = 0;
for(i = 1; i <= num; i++)
{
if (i%2 != 0)
{
sum += i;
System.out.print(i + " ");
}
}
return sum;
}
//Method for negative integers
public static int sumOfOdd_Negative(int num)
{
int i, sum = 0;
for(i = -1; i >= num; i--)
{
if (i%2 != 0)
{
sum += i;
System.out.println((i) + " ");
}
}
return sum;
}
public static int sumOfOddPostive(int num) {
int sum = 0;
for (int i = 1; i <= num; i++) {
if (i%2 != 0) {
sum += i;
if (i != 1) {
System.out.print("+ ");
}
System.out.print(i + " ");
}
}
System.out.println("= " + sum);
// int n = (num + 1)/2; sum = n*n;
return sum;
}
To have a "+" between the terms (one less than the number of terms),
one way is to skip the first (or last term).
It is questionable whether both calculation and output should be so mixed.
Of course the sum can be calculated without all those additions.
I guess you are not printing + as a character anywhere in your code snippet, try below snippet
public static int sumOfOdd_Postive(int num) {
int i, sum = 0;
for(i = 1; i <= num; i++) {
if (i%2 != 0) {
sum += i;
System.out.print(i + "");
if(i != num - 1){ //to avoid + at end of expression
System.out.print("+");
}
}
}
System.out.print("="+sum);
return sum;
}
You want a String so your method should return a String, not an int
Also, you can use StringBuilder in order to create a concatenated String.
Here is a naive implementation :
static String sumOdds(int limit) {
StringBuilder sb = new StringBuilder();
long sum = 0;
for (int i = 1; i <= limit; i++) {
if ( i%2 == 1 ) {
sum += i;
sb.append(i);
if (i + 2 <= limit) {
sb.append(" + ");
} else {
sb.append(" = ").append(sum);
}
}
}
return sb.toString();
}
That being said, as you only want odd or even numbers, there is no point to increment the step one by one and check modulos, you could directly start at 1 and increment steps by 2 :
static String sumOdds(int limit) {
StringBuilder sb = new StringBuilder();
long sum = 0;
for (int i = 1; i <= limit; i+=2) {
sum += i;
sb.append(i);
if (i + 2 <= limit) {
sb.append(" + ");
} else {
sb.append(" = ").append(sum);
}
}
return sb.toString();
}
Also, later, you will discover... Streams !
You can create a Stream of Integer and use some Collectors in order to do fancy things with them.
For example :
static IntStream oddStream(int limit) {
/*
* Here, you can also generate directly odd numbers without filtering
* but it is a bit out of scope.
* See : https://howtodoinjava.com/java8/generate-finite-infinite-stream/
*/
return IntStream.range(1, limit + 1).filter(i -> i % 2 == 1);
}
Then, you can use it to get all the values, map them to a String and collect them in a String, where the values are separated with " + "
String str = Main.oddStream(limit)
.mapToObj(Integer::toString)
.collect(Collectors.joining(" + "));
Also, you can use the same Stream in order to sum all the values :
long sum = Main.oddStream(limit).sum();
Which allows you to create the desired result like this :
static String sumEven(int limit) {
String str = Main.oddStream(limit)
.mapToObj(Integer::toString)
.collect(Collectors.joining(" + "));
long sum = Main.oddStream(limit).sum();
return str + " = " + sum;
}
Related
The problem is to display the first 50 prime numbers in 5 lines, each of which contains 10 numbers. I've created a program to output the first 50 prime numbers but I don't know how to split them so they output 10 numbers per line. I am a beginner level programmer and I really need help on this.
public class Lab4 {
public static void main(String[] args) {
int i = 0;
int num = 0;
String primeNumbers = " ";
for (i = 1; i <= 230; i++)
{
int counter = 0;
for (num = i; num >= 1; num--)
{
if (i % num == 0)
{
counter = counter + 1;
}
}
if (counter == 2)
{
primeNumbers = primeNumbers + i + " ";
}
}
System.out.println(primeNumbers);
}
}
You need to count how many items you already added and once you have 10 you need to put new line. Also I changed String to StringBuilder because concatenating in a loop is not very good, you can read about it here StringBuilder vs String concatenation
int i = 0;
int num = 0;
int lineCounter = 0;
StringBuilder primeNumbers = new StringBuilder();
for (i = 1; i <= 230; i++) {
int counter = 0;
for (num = i; num >= 1; num--) {
if (i % num == 0) {
counter = counter + 1;
}
}
if (counter == 2) {
primeNumbers.append(i).append(" ");
lineCounter++;
}
if (lineCounter == 10) {
primeNumbers.append(System.lineSeparator());
lineCounter = 0;
}
}
System.out.println(primeNumbers);
Just add this piece of code below after this line in your code: primeNumbers = primeNumbers + i + " ";
if (newLineCount == 10) {
primeNumbers += '\n';
newLineCount = 0;
}
newLineCount++;
Also init newLineCount before the loop: int newLineCount = 0;
Additionally, as mentioned in the comments, consider using StringBuilder instead of String, or even better ArrayList to store your numbers, then you can have method to print values from your ArrayList in whatever formatted way you want (with tabs, alignment, new lines...)
Here is the code that suits your needs. I haven't changed anything in your code, just added mine to suit your needs.
public class print_prime_numbers_10_per_line {
public static void main(String[] args) {
int i = 0;
int num = 0;
String primeNumbers = "";
for (i = 1; i <= 230; i++) {
int counter = 0;
for (num = i; num >= 1; num--) {
if (i % num == 0) {
counter = counter + 1;
}
}
if (counter == 2) {
primeNumbers = primeNumbers + i + " ";
}
}
String[] integerStrings = primeNumbers.split(" ");
int[] integers = new int[integerStrings.length];
for (int x = 0; x < integers.length; x++) {
integers[x] = Integer.valueOf(integerStrings[x]);
}
for (int g = 0; g < integers.length; g++) {
if (g % 11 == 0) {
System.out.println();
} else {
System.out.print(integers[g] + " ");
}
}
}
}
for my school project I have to create a program that outputs perfect numbers based on how many perfect numbers the user(teacher) want. The user can pick any number from 1-4 and it should display however many number the user chooses. Here is my current code. Please ignore the sumupTo, factorial, isprime, and the testGoldbach methods, please only look at the Perfect numbers method/code.
import java.util.Scanner;
public class MyMathB
{
public static int sumUpTo(int n)
{
int sum = 0;
for (int k = 1; k <= n; k++)
sum += k;
return sum;
}
public static long factorial(int n)
{
long f = 1;
for (int k = 2; k <= n; k++)
f *= k;
return f;
}
public static boolean isPrime(int n)
{
if (n <= 1)
return false;
int m = 2;
while (m * m <= n)
{
if (n % m == 0)
return false;
m++;
}
return true;
}
public static void PerfectNumbers(int number)
{
System.out.println("How many perfect numbers would you like to see? Please enter an integer from 1 to 4");
Scanner s = new Scanner(System.in);
int numbersToSee = s.nextInt();
int counts = 0;
for(counts = 0; counts <= numbersToSee; counts++)
{
for (int n = 5; n <= 10000; n++)
{
int temp = 0;
for(int i = 1; i <= number / 2; i++)
{
if (number % i == 0)
{
temp += i;
}
if (temp == number)
{
System.out.println(number);
}
}
}
}
}
public static boolean testGoldbach(int bigNum)
{
for (int n = 6; n <= bigNum; n += 2)
{
boolean found2primes = false;
for (int p = 3; p <= n/2; p += 2)
{
if (isPrime(p) && isPrime(n - p))
found2primes = true;
}
if (!found2primes)
{
System.out.println(n + " is not a sum of two primes!");
return false;
}
}
return true;
}
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
int n;
do
{
System.out.print("Enter an integer from 4 to 20: ");
n = kb.nextInt();
} while (n < 4 || n > 20);
kb.close();
System.out.println();
System.out.println("1 + ... + " + n + " = " + sumUpTo(n));
System.out.println(n + "! = " + factorial(n));
System.out.println("Primes: ");
for (int k = 1; k <= n; k++)
if (isPrime(k))
System.out.print(k + " ");
System.out.println();
System.out.println("Goldbach conjecture up to " + n + ": " + testGoldbach(n));
}
}
you didn't declare the variable "number" in your method.
Edit: you didn't SET the variable number to anything, I misworded my last statement.
This program gets 4 input from the user and prints out all the pairs except for the duplicate pairs. I wanted it print only the pairs that sum equals a prime number. I did the entire program there is no compilation error but in the output it prints to all pairs except the duplicate pair(i want it to print only the pair whose sum= a prime number) can anyone tell me what i am doing wrong
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Prime {
public static List<Integer> numbers = new ArrayList<>(); // a list of integers that was accepted, can be acced in the order they were added
public static Scanner input = new Scanner(System.in);
public static void main(String args[])
{
int inputs = 4;
input(inputs);
for(int i = 0; i < inputs; i++){
for(int j = 0+i; j < inputs; j++){
if(i != j)
System.out.println(numbers.get(i)+ " + " + numbers.get(j) + " = "+ isPrime(numbers.get(i) + numbers.get(j)));
}
} }
public static int isPrime (int sumPair)
{
boolean primeVal =true ;
if(sumPair < 2)
primeVal= false;
else if(sumPair ==2)
primeVal=true;
else if (sumPair % 2 == 0)
primeVal = false;
else
{
int stop = (int)Math.sqrt(sumPair);
for (int d = 3; d <= stop && primeVal; d = d + 2)
{
if (sumPair % d == 0)
primeVal = false;
}
}
return(sumPair);
}
public static void input(int inputNumbers)
{
while(numbers.size() < inputNumbers){ // while there is more inputs needed
System.out.print("Enter a positive integer: ");
int num = input.nextInt();
if(num > 0) // if the input is valid
numbers.add(num);
else // if the input is not valid
while (num <= 0) { // while the input is not valid
System.out.print("Enter a positive integer: ");
num = input.nextInt(); // get the next int if it wasn't valid
if(num > 0) { // if the input gets valid
numbers.add(num);
}
}
System.out.println("Thank you.");
}
}
public static int sumPair(int num1, int num2)
{
return num1 + num2;
}
}
You go to a lot of trouble to compute a boolean primeVal which tells whether the input be true or false, but you never actually return this value. Try this instead:
public static boolean isPrime (int sumPair) {
boolean primeVal = true;
if (sumPair < 2 || sumPair % 2 == 0) {
primeVal = false;
}
else {
int stop = (int)Math.sqrt(sumPair);
for (int d=3; d <= stop; d += 2) {
if (sumPair % d == 0) {
primeVal = false;
break;
}
}
}
return primeVal;
}
Use this main() method:
public static void main (String args[]) {
int inputs = 4;
input(inputs);
for (int i=0; i < inputs-1; i++) {
for (int j=i+1; j < inputs; j++) {
boolean prime = isPrime(numbers.get(i) + numbers.get(j));
if (prime) {
System.out.println(numbers.get(i) + " + " + numbers.get(j));
}
}
}
}
Your condition to determine if you print the current pair or not is if(i != j), so it will only print if i is different from j (duplicate).
You made a nice isPrime function, you should call it.
You made your isPrime function return an int, and I'm pretty sure it should return a boolean instead. Also, it returns the argument you gave it, so it does virtually nothing except spend time in a potentially expensive operation. Perhaps should it return primeVal instead.
Your code should look like:
for(int i = 0; i < inputs; i++){
for(int j = 0+i; j < inputs; j++){
ni = numbers.get(i);
nj = numbers.get(j);
if(isPrime(ni+nj)){
System.out.println(ni + " + " + nj + " = "+ (ni + nj));
}
}
}
What this does is get the numbers for indexes i and j and store them in ni and nj respectively. Then, it checks it their sum is prime. If it is, then it prints the sum.
My assignment reads:
Write a program that finds all of the prime numbers between one and some number that you allow the user to input.
Find the prime numbers between 0 and the number the user inputs.
Print these prime numbers, one per line.
After each prime number, add a colon and then print out all the non-prime numbers that were eliminated.
Basically, these non-prime numbers are the multiples of the primes.
For example, the output will look like this:
2: 4 6 8 10 12 14 16 18...
3: 9 15 21 27
I did prime numbers. I can not figure out how to calculate and display multiples? Help, please!
package assignment4;
import java.util.Scanner;
public class Assignment4 { /**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
final int START = 1;
System.out.print("Enter the end number number : ");
int end = s.nextInt();
System.out.println("List of prime numbers between " + START + " and "
+ end);
for (int i = START; i <= end; i++) {
if (isPrime(i)) {
System.out.println(i + ":");
}
}
}
public static boolean isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i < Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;}
}
I am assuming that you want to have print the multiples until the end number. You could nest a while loop that multiplies the prime number as follows:
for (int i = START; i <= end; i++) {
if (isPrime(i)) {
System.out.print(i + ": "); //Changed to print so that the multiples are on the same line
int multiple = i * 2;
while (multiple <= end) {
multiple += i;
System.out.print(multiple + ", ");
}
System.out.println("");
}
}
Displaying multiples would be easy if you were sieving using sieve of Erathrosthenes. You create an array of numbers from 2 to n. start with 2, mark non-prime all its multiples: 2 4 6... print them. Choose next prime number (i.e. the number which was not marked unprime) i.e. 3, mark non-prime all its multiples (which haven't been already): 9 15 ... and so on.
Simplest Solution:
boolean[] x = new boolean[N];// x[i] is true when i is not prime
for(int i=2;i<N;i++){
if(!x[i]){
System.out.print(i+" : ");
for(int j=i*i;j<N;j+=i){
if(!x[j])
System.out.print(j+" ");
x[j]=true;
}
System.out.println();
}
}
Please check below answer for your requirement,
package assignment4;
import java.util.*;
import java.lang.*;
import java.io.*;
public class Assignment4
{
public static List<Integer> primeNumbers = new ArrayList<>();
public static String strOtherData[];
public static void main (String[] args) throws java.lang.Exception
{
final int START = 1;
System.out.print("Enter the end number number : ");
int end = s.nextInt();
System.out.println("List of prime numbers between " + START + " and " + end);
for (int i = START; i <= end; i++) {
if (isPrime(i)) {
primeNumbers.add(i);
}
}
strOtherData = new String[primeNumbers.size()];
for (int i = START; i <= end; i++) {
isMultiple(i);
}
int tempCount = 0;
for(Integer currentNumber : primeNumbers)
{
System.out.print(currentNumber + ": \t");
if(strOtherData.length > tempCount)
{
System.out.print(strOtherData[tempCount] + "\n\n");
}
tempCount++;
}
}
public static boolean isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i <= n/2; i++)
{
if (n % i == 0)
{
return false;
}
}
return true;
}
public static void isMultiple(int n)
{
if (n <= 1) {
return;
}
if(isPrime(n))
return;
int count = 0;
for(Integer currentInt : primeNumbers)
{
if(strOtherData[count] != null)
{
strOtherData[count] += "," + n;
}
else
{
strOtherData[count] = "" + n;
}
count++;
}
}
}
I'm new to Java and I'm trying to make a program that allows the user to input 100 numbers and if the user writes '0', then the program is suppose to print the smallest, largest, sum and all the numbers. I got all that to work but not to exit and print it all. My teacher said something about using a while loop, but how is that possible when you have a for loop?
Regards
public static void main(String[] args) {
int[] list = new int[100];
int min = 0;
int max = 0;
int sum = 0;
boolean first = true;
Scanner scan = new Scanner(System.in);
while(list[i] != 0) {
for (int i = 0; i < list.length; i++) {
System.out.print("Enter number (0 to exit) " + (1 + i) + ":");
list[i] = scan.nextInt();
}
for (int i = 0; i < list.length; i++) {
if (first == true) {
min = list[i];
first = false;
}
if (list[i] < min) {
min = list[i];
}
else if (list[i] > max) {
max = list[i];
}
sum = list[i] + sum;
}
if (list[i] == 0) {
System.out.print("Numbers are: " + list[0] + ", ");
for (int i = 1; i < list.length; i++)
System.out.print(list[i] + ", ");
System.out.println();
System.out.println("Smallest number is: " + min);
System.out.println("Largest numeber is: " + min);
System.out.println("Sum is: " + sum);
}
}
}
}
You only need one while loop to do this and additionally a for loop just to print the array if you want:
Scanner scan = new Scanner(System.in);
int i = 0;
int sum = 0;
int maxValue = Integer.MIN_VALUE;
int[] history = new int[100];
System.out.println("INPUT:");
int option = scan.nextInt();
while (option != 0 && i <= 100)
{
if (option > maxValue)
maxValue=option;
sum += option;
history[i] = option;
option = scan.nextInt();
i++;
}
System.out.println("OUTPUT: \n" + "SUM: " + sum + "\n MAX VALUE: " + maxValue);
for (int x : history)
System.out.print(x + "");
Here's the body of the method which will do what you've been asked. I have not used a while loop (but in fact, a for-loop is a kind of a while-loop internally).
int size = 100; // Set the number of numbers to input.
int[] list = new int[size]; // Create an array with 'size' elements.
int min = Integer.MAX_VALUE; // Set the highest possible integer as start value.
int max = 0; // Set the minimum to zero, assuming that the user won't input negative numbers.
int sum = 0; // Initialize the sum of the numbers in the list.
Scanner scan = new Scanner(System.in);
for (int i = 0; i < size; i++) { // Run 'size' times the process of inputting a number.
System.out.print("Enter number (0 to exit) " + (i + 1) + ": ");
int number = scan.nextInt();
if (number == 0) { // Quit program if input equals '0'
System.out.println("Exiting...");
break;
}
list[i] = number; // Add the current number to the list
sum += number; // Add the number to the total
if (number < min) { // If the number is smaller than the previous one, set this number as the smallest
min = number;
}
if (number > max) { // If the number is greater than the previous smallest number, set this number as the greatest
max = number;
}
}
// Output all numbers in the list
for (int i = 0; i < list.length; i++) {
if (list[i] != 0) {
System.out.print((i == 0 ? "" : ", ") + list[i]);
}
}
// You see the snippet (i == 0 ? "" : ", ")
// That is a shorthand if-else statement:
// If i equals 0, then "" (empty string), else ", " (comma and space).
// The statement
// System.out.print((i == 0 ? "" : ", ") + list[i])
// is the same as
// if (i == 0) {
// System.out.println("") + list[i];
// }
// else {
// System.out.println(", ") + list[i];
// }
System.out.println("Smallest number is: " + min);
System.out.println("Largest numeber is: " + max);
System.out.println("Sum is: " + sum);
You have muddled code. Better to use a pattern like this:
while (true) {
// read next
if (input == 0)
break;
}