I'm solving a problem to find all the multiples of 3 and 5 within a number that is inputted from the user.
I want to show all the multiples and their sum to the user.
I can't find a way to add the values to the array containing the multiples.
Here is the code:
import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.*;
public class application {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Input the number from user:
System.out.println("Enter a number to calculate the sum of all the multiples of 3 or 5 below it: ");
int number = input.nextInt();
int i = 1;
int[] arr = {};
System.out.println("The multiples of 3 and 5 below the number " + number + " are: ");
while(i < number) {
if (i % 3 == 0 || i % 5 == 0 ) {
System.out.print(i + ",");
arr = Arrays.copyOf(arr, arr.length + 1);
arr[arr.length - 1] = i;
}
i++;
}
int sum = IntStream.of(arr).sum();
System.out.println("The sum of these multiples is: " + sum);
//Thank you :D
}
}
Try just adding the multiples together as they are found.
You do not need an array to store them since your code is a) printing out the multiple found and then b) printing out the sum of the multiples
instead of array you can direct sum of the multiple 3 and 5
int sum = 0
inside if statement
if (i % 3 == 0 || i % 5 == 0 ) {
System.out.print(i + ",");
sum += i;
//arr = Arrays.copyOf(arr, arr.length + 1);
//arr[arr.length - 1] = i;
}
and print out the sum
Related
I'm making a program that counts how many times each digit (0-9) occurs in each number between 1 to 100. At the end it will say something like:
The digit 0 showed up ____ times between 1-100
The digit 1 showed up ____ times between 1-100
and so forth.
This is what I have:
public class CountEachDigit {
public static void main(String[] args) {
int counter =0;
int[] digit = new int[10];
for (int i=1;i<=100;i++) {
for (int j=0;j<=9;j++){
try{
String a = String.valueOf(i);
String b = String.valueOf(j);
if (b.equals(a.charAt(0)))
counter++;
digit[j]=counter;
} catch (Exception e){
continue;
}
try{
String a = String.valueOf(i);
String b = String.valueOf(j);
if (b.equals(a.charAt(1)))
counter++;
digit[j]=counter;
} catch (Exception e){
continue;
}
try{
String a = String.valueOf(i);
String b = String.valueOf(j);
if (b.equals(a.charAt(2)))
counter++;
digit[j]=counter;
} catch (Exception e){
continue;
}
}
}
for (int j =0;j<=9;j++){
System.out.println("The number "+j+" appears "+digit[j]+" times between 1 - 100.");
}
}
}
I tried changing the charAt each digit to a String to count the occurrence using the try and catch. No dice so far.
You do not need a string operations. You have to use x % 10 to get the last digit, and then x \= 10, to remove this last digit.
public class CountEachDigit {
public static void main(String... args) {
final int lo = 1;
final int hi = 100;
int[] digits = countDigits(lo, hi);
for (int i = 0; i < 10; i++)
System.out.format("The number %d appears %d times between %d - %d.\n", i, digits[i], lo, hi);
}
private static int[] countDigits(int lo, int hi) {
int[] digits = new int[10];
for (int i = lo; i <= hi; i++) {
int val = i;
do {
digits[val % 10]++;
} while ((val /= 10) > 0);
}
return digits;
}
}
Demo:
The number 0 appears 11 times between 1 - 100.
The number 1 appears 21 times between 1 - 100.
The number 2 appears 20 times between 1 - 100.
The number 3 appears 20 times between 1 - 100.
The number 4 appears 20 times between 1 - 100.
The number 5 appears 20 times between 1 - 100.
The number 6 appears 20 times between 1 - 100.
The number 7 appears 20 times between 1 - 100.
The number 8 appears 20 times between 1 - 100.
The number 9 appears 20 times between 1 - 100.
Have an array with int[10] to count the occurrences for each digit.
Then have a function that traverses a string and for each digit it finds increases the correct field in the array.
Then have a loop over numbers from 1 to 100 which converts that number to string and feeds it into the function.
Finally print the array values.
In code this may look like
public class Test {
static int[] occurrences = new int[10];
static void checkOccurrences(String s) {
for (char c: s.toCharArray()) {
if (Character.isDigit(c)) {
occurrences[ c - '0' ]++;
}
}
}
public static void main(String[] args) {
for (int i=1; i<=100; i++) {
String s = String.valueOf(i);
System.out.println("checking "+s);
checkOccurrences(s);
}
System.out.println(Arrays.toString(occurrences));
}
}
and it prints
checking 1
checking 2
checking 3
...
checking 99
checking 100
[11, 21, 20, 20, 20, 20, 20, 20, 20, 20]
In case you or future readers want to see a stream approach, which I doubt, here's what I did just for fun: Stream over the range [1 - 100], convert and map to String, split each String at each charachter such that, for example "42" becomes a stream of "4" and "2", collect to map using digit as key and count of occurrence as value and finally print.
import java.util.Arrays;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
// ...
public static void main(String[] args) {
IntStream.rangeClosed(1, 100)
.mapToObj(String::valueOf)
.flatMap(s -> Arrays.stream(s.split("")))
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.forEach((k,v) -> System.out.printf("The digit %s showed up %d times between 1-100%n", k, v));
}
Instead of converting a number to string and then loop over its digits, you can also take the remainder by 10, i.e., the last digit, and then divide the number by 10 to "shift" it to the right.
For example, 45 % 10 == 5, and 45 / 10 == 4.
After you exit the while loop, your number is a single-digit number, so you have to count again that digit.
public class CountEachDigit {
public static void main(String[] args) {
int[] digits_count = new int[10];
int min = 1;
int max = 100;
for (int i = min; i <= max; ++i) {
int number = i;
while (number > 9) {
int last_digit = number % 10;
digits_count[last_digit] += 1;
number /= 10;
}
digits_count[number] += 1;
}
for (int i = 0; i < 10; i++) {
int count = digits_count[i];
System.out.println("Digit " + i + " appears " + count + " times in range [" + min + ", " + max + "]");
}
}
}
Using strings:
for (int i = 1; i <= 100; i++) {
String num = String.valueOf(i);
for(int j=0;j<num.length();j++){
//substracting 0 to get the integer value
counts[num.charAt(j)-'0']++;
}
}
for (int i = 0; i < 10; i++) {
System.out.println("The digit " + i + " showed up " + counts[i] + " times between 1-100.");
}
You can do it using by streaming and collecting in a map.
allocate a map to hold the counts
stream the values from 1 to 100 inclusive
within mapMulti
get the last digit by using the remainder % operator
accept the digit and place on the stream
expose the next digit by dividing by 10
Now collect the digits in the map, creating a frequency count as they occur. Each digit will the the key and the value will be the count.
Map<Integer, Integer> counts = IntStream.rangeClosed(1, 100)
.mapMulti((val, consumer) -> {
while (val > 0) {
consumer.accept(val % 10);
val /= 10;
}
}).boxed()
.collect(Collectors.toMap(i -> i, i -> 1, Integer::sum));
counts.forEach((digit, count) -> System.out
.println(digit + " occurs " + count + " times."));
prints
0 occurs 11 times.
1 occurs 21 times.
2 occurs 20 times.
3 occurs 20 times.
4 occurs 20 times.
5 occurs 20 times.
6 occurs 20 times.
7 occurs 20 times.
8 occurs 20 times.
9 occurs 20 times.
I am trying to finding the sum of each in the below code in java.What changes should i have to made in this code.
import java.io.IOException;
class as {
static void printSubsets(int set[]) {
int n = set.length;
for (int i = 0; i < (1 << n); i++) {
for (int j = 0; j < n; j++) {
if ((i & (1 << j)) > 0) {
System.out.print(set[j] + " ");
}
}
System.out.println();
}
}
public static void main(String[] args) {
int set[] = { 1, 2, 3 };
printSubsets(set);
}
}
Output of above code is:
1
2
1 2
3
1 3
2 3
1 2 3
I want To Multiply each element of subset by its last number for e.g.
1*1=1
2*2=4
1*2+2*2=6
3*3=9
likewise all elements
and lastly generate sum of all these subset 1+4+6+9+.. and so on.
Above code also print null set and subset are in order.How this program can be edited to make changes such that it does'nt print null set and print random substring.
As far as I understand your question, you want to multiply all the elements with each other and print out each step of iteration with the result. Here you are:
static void printSubsets(int set[]) {
int sum = 0;
for (int i=0; i<set.length; i++) {
for (int j=i; j<set.length; j++) {
int var = set[i] * set[j];
sum += var;
System.out.println("( " + set[i] + " * " + set[j] + " = " + var + " ) -> sum=" + sum);
}
}
System.out.println("final sum=" + sum);
}
In case of input [1,2,3], the sum is supposed to grow according my algorithm by:
1, 3, 6, 10, 16 up to 20
Just a note about << shift operator which shifts a bit pattern to the left. Let's say that number 2 is understood as 10 in binary. Shifting this number by 2 << 4 will result 100000 in binary that is understood as 32 in decimal. I am not sure you really need this pattern.
import java.util.Scanner;
public class OddSum {
public static void main(String[] args) {
int num;
int i = 1;
int sum = 0;
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
num = input.nextInt();
input.close();
while (i<=num) {
i += 2;
sum +=i;
}
System.out.println("The sum of odd numbers between 1 and" + num + "is: " + sum);
}
}
I wrote this code to sum up the odd numbers from 1 to a number entered.
Now, when I entered 8, I got the output as 24, against the desired output 16.
Can you tell me what went wrong?
You are incrementing the variable before performing summation .
while (i<=num) {
sum +=i;
i += 2;
}
You should add i to sum before adding to 2 to i. Thus, once i goes past num, the while loop will no longer execute.
import java.util.Scanner;
public class OddSum {
public static void main(String[] args) {
int num;
int i = 1;
int sum = 0;
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
num = input.nextInt();
input.close();
while (i<=num) {
// add i to sum before adding 2 to i
sum += i;
i += 2;
}
System.out.println("The sum of odd numbers between 1 and" + num + "is: " + sum);
}
Lets debug the code together:
after taking the number it would go to i<=num that while condition. Great, Then instead of getting sum it would + again 2 which cause 3. So what's happen? First case, 1 is not added before and first iteration value 1 is lose. That means whenever, you enter the loop. It goes increases before adding the previous value. So, rewrite the code this way:
while (i<=num) {
sum +=i;
i += 2;
}
You may use for instead:
for(int i=1;i<=num;i+=2){
sum +=i;
}
You're incrementing i before you sum it, instead of afterwards:
while (i <= num) {
sum +=i;
i += 2;
}
It's worth noting, though, that these kind of issues, where the loop variable is incremented by a constant, are often more convenient to write with a for loop:
for (int i = 1; i <= num; i += 2) {
sum += i;
}
Or better yet, if you're using Java 8, by collecting a stream:
int sum = IntStream.rangeClosed(1, num).filter(i -> i % 2 != 0).sum();
The reason why the result for your example with N = 8 gives 24 is because when i reaches value 7, the loop is continued and is added the value 9 to your sum too and you forget to add the first odd number: 1, because you start over from adding directly 3 to your sum.
You can either switch the statements between each other, either use a for loop instead of while:
for(int i = 1; i <= num; i += 2) {
sum += i;
}
Beginner here. So I want to write a program that prints out all the prime numbers up to the number the user entered. E.g., user enters 5, program prints out 2 and 3. That part I understand, however what I am struggling with, is what if I want the program to print out whether the number the user entered is a prime or not (simple yes or no) IF the entered number is bigger than, let's say, 50. Here is code for first part:
public class Primes {
public static void main(String args[]) {
System.out.println("All primes up to: ");
int num = new Scanner(System.in).nextInt();
System.out.println("Prime numbers from 1 to " + num + " are: ");
for(int number = 2; number<=num; number++){
if(isPrime(number)){
System.out.println(number);
}
}
}
public static boolean isPrime(int number){
for(int i=2; i<number; i++){
if(number%i == 0){
return false;
}
}
return true;
}
}
I honestly can't wrap my around as to what I should be doing next. My first program ever ("Hello world" does not count ;P).
Edit :
Your current code seems to work fine.
As per your doubt as mentioned in one of the comments : Yes, but where do I add if statement that does the following: if the number entered is below 50, then the program prints out all the prime numbers up to the entered number. If the number the user entered is bigger than 50, it tells only whether the entered number is prime or not ( simply "It's a prime" or "No, it's not a prime"). Hope that made things clearer
The check you need to put is after you take the input :
int num = new Scanner(System.in).nextInt();
if( number > 50 )
{
if(isPrime(number))
{
// print out is prime
}
// print out it is not prime
}
else
{
System.out.println("Prime numbers from 1 to " + num + " are: ");
for(int number = 2; number<=num; number++){
if(isPrime(number)){
System.out.println(number);
}
}
}
SUGESTIONS :
However, just to touch upon the algorithmic part, I would recommend using Sieve of Eratosthenes for picking out all the prime numbers within a given range, as you need in your case.
Example :
To find all the prime numbers less than or equal to 30, proceed as follows:
First generate a list of integers from 2 to 30:
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
Strike (sift out) the multiples of 2 resulting in:
2 3 5 7 9 11 13 15 17 19 21 23 25 27 29
The first number in the list after 2 is 3; strike the multiples of 3 from the list to get:
2 3 5 7 11 13 17 19 23 25 29
The first number in the list after 3 is 5; strike the remaining multiples of 5 from the list:
2 3 5 7 11 13 17 19 23 29
The first number in the list after 5 is 7, but 7 squared is 49 which is greater than 30 so the process is finished. The final list consists of all the prime numbers less than or equal to 30.
Here's the code attached for reference ( Disclaimer : I'm picking up this code here from this site. Just pasted it here for more immediate visibility).
Code :
public class PrimeSieve {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
// initially assume all integers are prime
boolean[] isPrime = new boolean[N + 1];
for (int i = 2; i <= N; i++) {
isPrime[i] = true;
}
// mark non-primes <= N using Sieve of Eratosthenes
for (int i = 2; i*i <= N; i++) {
// if i is prime, then mark multiples of i as nonprime
// suffices to consider mutiples i, i+1, ..., N/i
if (isPrime[i]) {
for (int j = i; i*j <= N; j++) {
isPrime[i*j] = false;
}
}
}
// count primes
int primes = 0;
for (int i = 2; i <= N; i++) {
if (isPrime[i]) primes++;
}
System.out.println("The number of primes <= " + N + " is " + primes);
}
}
Try this..
int j = 2; //variable
int result = 0; //variable
int number = 0; //variable
Scanner reader = new Scanner(System.in); //Scanner object
System.out.println("Please enter a number: "); //Instruction
number = reader.nextInt(); //Get the number entered
while (j <= number / 2) //start loop, during loop j will become each number between 2 and
{ //the entered number divided by 2
if (number % j == 0) //If their is no remainder from your number divided by j...
{
result = 1; //Then result is set to 1 as the number divides equally by another number, hergo
} //it is not a prime number
j++; //Increment j to the next number to test against the number you entered
}
if (result == 1) //check the result from the loop
{
System.out.println("Number: " + number + " is Not Prime."); //If result 1 then a prime
}
else
{
System.out.println("Number: " + number + " is Prime. "); //If result is not 1 it's not a prime
}
this is more efficient way tough:-
public boolean isPrime(int n) {
// fast even test.
if(n > 2 && (n & 1) == 0)
return false;
// only odd factors need to be tested up to n^0.5
for(int i = 3; i * i <= n; i += 2)
if (n % i == 0)
return false;
return true;
}
however what I am struggling with, is what if I want the program to print out whether the number the user entered is a prime or not (simple yes or no).
Your current isPrime function seems to work, so just ask for a number and test it.
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
System.out.println("Enter a number (is it prime): ");
int num = scanner.nextInt();
if (isPrime(num)) {
System.out.printf("%d yes%n", num);
} else {
System.out.printf("%d no%n", num);
}
}
Or with a ternary,
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
System.out.println("Enter a number (is it prime): ");
int num = scanner.nextInt();
System.out.printf("%d %s%n", num, isPrime(num) ? "yes" : "no");
}
Edit Based on your comment, move your print up sequence to a method
public static void primesUpTo(int num) {
System.out.println("Prime numbers from 1 to " + num + " are: ");
for (int number = 2; number <= num; number++) {
if (isPrime(number)) {
System.out.println(number);
}
}
}
Then
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
System.out.println("Enter a number (is it prime): ");
int num = scanner.nextInt();
if (num > 50) {
System.out.printf("%d %s%n", num, isPrime(num) ? "yes" : "no");
} else {
primesUpTo(num); // <-- call the method above.
}
}
If i understand the question right:
If user enteres number lesser than or equal to 50, then print all primes that are lesser than that number.
Otherwise, just write if inputted number is a prime.
With already existing isPrime() method:
int num = new Scanner(System.in).nextInt();
if (num <= 50) {
System.out.println("Prime numbers from 1 to " + num + " are: ");
for (int number = 2; number <= num; number++) {
if (isPrime(number)) {
System.out.println(number);
}
}
} else { //num > 50
if(isPrime(num)) {
System.out.println(num + " is prime.");
} else {
System.out.println(num + " isn't prime.");
}
}
I'm trying to make a simple program that will display 20 random numbers between 1 and 100 and then print out which numbers are divisible by 3 and equivalent to 1%3 and 2%3. It seems to work just fine but I've noticed it only works with the very last number in the list. What am I missing to include all the numbers in the search for my math? Thank you in advance for any help I can get!
import java.util.Random;
public class Lab5 {
public static void main(String[] args) {
Random rnd = new Random();
int repeat = 19;
int n = 0;
for(int i=0;i<=repeat;i++){
n = rnd.nextInt(100)+1;
System.out.print(n+", ");
}
System.out.println();
System.out.println("-------------------------------------");
if(n % 3 == 0){
System.out.println("Numbers divisible by three: "+n+(", "));
}else{
System.out.println("Numbers divisible by three: NONE");
}
System.out.println("-------------------------------------");
if(n == 1 % 3){
System.out.println("Numbers equivalent to one modulo three: "+n+(", "));
}else{
System.out.println("Numbers equivalent to one modulo three: NONE");
}
System.out.println("-------------------------------------");
if(n == 2 % 3){
System.out.println("Numbers equivalent to two modulo three: "+n+(", "));
}else{
System.out.println("Numbers equivalent to two modulo three: NONE");
}
}
}
It is only printing the last number because the check if the number is divisible, etc is not in your for loop at the top. Simply copy and paste all of the code below it into your for loop and it should work as you intended.
You also have an error here: if (n == 1 % 3), it is legal but will check if n is equal to the remainder of 1 / 3. I don't think that is what you wanted to achieve, so correct it like this: if (n % 3 == 1) as Ypnypn suggested.
Your n is declared outside of the loop body, so its value will persist. However, since you are overwriting n in each loop iteration, only the last value of n will persist and will be used by other parts of the program.
As Ypnypn has said, correct your use of modulo, and as Arbiter and deanosaur have suggested, move the rest of the program logic inside the for loop
The correct syntax for modulus is n % 3 == 2. The current code n == 2 % 3 means n == 0, since the order of operations in Java requires that modulus is evaluated before equality.
You are putting all the output statements (System.out.println()) outside your loop, so it only outputs the last value.
Move your output statements so they are inside your loop:
public static void main(String[] args) {
Random rnd = new Random();
int repeat = 19;
int n = 0;
int[] numbers = new int[3]; // To hold how many numbers have modulo 0, 1 or 2
for(int i = 0; i <= repeat; i++) {
n = rnd.nextInt(100)+1;
System.out.print(n+", ");
if(n % 3 == 0)
System.out.println("The number " + n + " is divisible by 3");
else
System.out.println("" + n + " modulo 3 = " + n % 3);
numbers[n % 3]++;
}
System.out.println("Numbers divisible by 3: " + numbers[0]);
System.out.println("Numbers with modulo 3 = 1: " + numbers[1]);
System.out.println("Numbers with modulo 3 = 2: " + numbers[2]);
}
Well .. you did not calculate anything in the loop, so your print statements work the last value of n after you exited the loop. Try something like
package com.example.modulo;
import java.util.Random;
public class Modulo {
public static void main(String[] args) {
Random rnd = new Random();
int repeat = 19;
int n = 0;
int[] nMod = new int[3];
nMod[0] = 0;
nMod[1] = 0;
nMod[2] = 0;
for (int i = 0; i <= repeat; i++) {
n = rnd.nextInt(100) + 1;
nMod[n%3] = nMod[n%3] + 1;
System.out.print(n + " (" + n%3 + "), ");
}
System.out.println();
System.out.println("-------------------------------------");
System.out.println("Numbers divisible by three: " + nMod[0] + (", "));
System.out.println("Numbers equivalent to one modulo three: " + nMod[1] + (", "));
System.out.println("Numbers equivalent to two modulo three: " + nMod[2] + (", "));
}
}