Why can i not use the OR-operator in a for-loop? - java

I am a beginner in Java. I want to write a short program to test, if you get for all numbers from 1 to 10000 a 4 or a 1 in the end at every time, if you continue taking each digit of it and squaring it and then adding them together. (Sorry, for my bad english)
for example:
24
2 * 2 + 4 * 4 = 18
1 * 1 + 8 * 8 = 65
6 * 6 + 5 * 5 = 61
...
Therefore, the code:
public class Main {
public static void main(String[] args) {
for (int i = 1; i < 100000; i++) {
for (int j = i; j != 4 || 1; ) {
int k = j % 10000;
int l = k % 1000;
int m = l % 100;
int n = m % 10;
int jj = j / 10000;
int kk = k / 1000;
int ll = l / 100;
int mm = m / 10;
int nn = n;
int number = jj * jj + kk * kk + ll * ll + mm * mm + nn * nn;
System.out.print(number);
j = number;
}
System.out.println();
}
}
}
But my console tells me that i can't use the operator "||" at this function. Can anyone explain to me why, as well as what I have to do?
Thanks in advance.
I tried using "|", but that also didn't work.

Related

Check every permutation of a number for primality

I'm working on this problem https://projecteuler.net/problem=49 .
This is the function to check every permutation of a number(4 digit) passed to it, and check them for primality, and if there are more than 2 (ie 3) print the numbers.
the output I'm getting is a never ending sequence of numbers. What am I doing wrong?
P.s- pretty sure it has to do with the repetition of digits, can't figure out how to work around it.
void checkperm(int a) {
int w, x, y, z = 0;
int count = 0;
w = a % 10;
x = (a % 100 - w) / 10;
y = (a % 1000 - (10 * x + w) / 100);
z = a - (y * 100 + x * 10 + w)/1000;
System.out.println(w+x+y+z); /*test*/
int[] data;
data = new int[] { w, x, y, z };
int[] num = new int[100];
for (int m = 0; m < 4; m++) {
for (int n = 0; n < 4; n++) {
for (int o = 0; o < 4; o++) {
for (int p = 0; p < 4; p++) {
if (true) {
int gnaw = 1000 * data[m] + 100 * data[n] + 10 * data[o] + data[p];
if (checkprime(gnaw)) {
num[count] = gnaw;
count++;
}
}
}
}
}
}
if (count > 2)
for (int h = 0; h < 4; h++) {
System.out.println(num[h]);
}
}
the way you're calculating w, x, y and z is wrong.
what it should be -
int temp = a;
w = temp%10;
temp = temp/10;
x = temp%10;
temp = temp/10;
y = temp%10;
temp = temp/10;
z = temp;
This is just logic correction from your code. Ideally all this should happen in a loop.
This will help assuming your rest of code is logically correct (which I haven't gone through).

Program to generate and print all the "anagrams" of a number without using array

This is a Java program to generate and print all the possible "Anagrams" of a four digit number without using an array. Here is what I've been able to do so far:
import java.util.*;
class Anag {
public static void main() {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int d = n % 10;
n = n / 10;
int c = n % 10;
n = n / 10;
int b = n % 10;
n = n / 10;
int a = n;
int w = a, x = b, y = c, z = d, co, i, j;
System.out.println(w * 1000 + x * 100 + y * 10 + z * 1);
for (i = 1; i <= 4; i++) {
for (j = 1; j <= 3; j++) {
if (j % 3 == 1) {
co = w;
w = x;
x = co;
System.out.println(w * 1000 + x * 100 + y * 10 + z * 1);
}
if (j % 3 == 2) {
co = x;
x = y;
y = co;
System.out.println(w * 1000 + x * 100 + y * 10 + z * 1);
}
if (j % 3 == 0) {
co = y;
y = z;
z = co;
System.out.println(w * 1000 + x * 100 + y * 10 + z * 1);
}
}
}
}
}
Using the above code, I've been able to generate 12 "Anagrams", but I cannot figure out how to generate the remaining 12 (there should be 24 in total). Does anyone have any ideas?
The following algorithm should work for you. In short, you shiftrotate the number and for every 4 anagrams you swap first two digits, but after the 12th anagram you swap 1st and 3rd digit.
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int d = n % 10;
n = n / 10;
int c = n % 10;
n = n / 10;
int b = n % 10;
n = n / 10;
int a = n;
int t;
for (int i = 0; i < 24; i++) {
System.out.println(a * 1000 + b * 100 + c * 10 + d);
if (i == 11) {
t = a;
a = c;
c = t;
}
if (i % 4 == 3) {
t = a;
a = b;
b = t;
} else {
t = a;
a = b;
b = c;
c = d;
d = t;
}
}
}

Need help writing a java program that adds multiple digits?

I am trying to write this java program that asks a user for a number and counts the number of digits a number has and multiplies each digit to it's decimal value. For example I enter 546: The program should say this number has 3 digits and should multiply:
5*100=500
4*10=40
1*6=6
So far this is my code: The problems I am having with this code is that it's not counting the right amount of digits. If I enter 545 it says there is only one digit, and when it goes to divides it doesn't give the right answer.
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a number: ");
int n = keyboard.nextInt();
int i;
for (i = 0; n > 0; i++) {
n /= 10;
for (i = 0; n > 0; i++) {
n /= 10;
System.out.println((n%100000) / 10000);
System.out.println((n%10000) / 1000);
System.out.println((n%1000) / 100);
System.out.println((n%100) / 10);
System.out.println(n%10);
}
System.out.println("Number of digits: " + i);
}
}
The issue is that you have a set of nested for loops that both call n /= 10. It is easier to see if you indent everything:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a number: ");
int n = keyboard.nextInt();
int i;
for (i = 0; n > 0; i++) {
n /= 10;
for (i = 0; n > 0; i++) {
n /= 10;
System.out.println((n%100000) / 10000);
System.out.println((n%10000) / 1000);
System.out.println((n%1000) / 100);
System.out.println((n%100) / 10);
System.out.println(n%10);
}
System.out.println("Number of digits: " + i);
}
}
After removing this, the code seems to work as intended, and tells you that 545 does, in fact have 3 digits. Here is the revised code:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a number: ");
int n = keyboard.nextInt();
int i;
for (i = 0; n > 0; i++) {
n /= 10;
System.out.println((n%100000) / 10000);
System.out.println((n%10000) / 1000);
System.out.println((n%1000) / 100);
System.out.println((n%100) / 10);
System.out.println(n%10);
}
System.out.println("Number of digits: " + i);
}
Seems like you trying to do the same task, by using arbitrary values. Instead try to incorporate some generic sort of an algorithm. Somethingy on the lines of this posted example:
public class CountDigits {
private void performTask () {
int number = 546;
int temp = number;
int digit = 0;
int counter = 1;
while ( temp != 0 ) {
digit = temp % 10;
System.out.println ( digit + " * " + getMultiplier ( counter ) + " = " + ( digit * getMultiplier ( counter ) ) );
++counter;
temp /= 10;
}
}
private int getMultiplier ( int power ) {
int value = 1;
for ( int i = 1; i < power; ++i ) {
value *= 10;
}
return value;
}
public static void main ( String[] args ) {
new CountDigits ().performTask ();
}
}
OUTPUT:
C:\Mine\java\bin>java CountDigits
9 * 1 = 9
1 * 10 = 10
1 * 100 = 100
1 * 1000 = 1000
C:\Mine\java\bin>java CountDigits
6 * 1 = 6
4 * 10 = 40
5 * 100 = 500
int n = 546;
for( int i = 0, dig = (int) Math.log10( n ) + 1; i < dig; ++i )
{
int mult = (int) Math.pow( 10, dig - i - 1 );
int a = (n / mult) % 10;
System.out.println( a + " * " + mult + " = " + (a * mult) );
}
Results in:
5 * 100 = 500
4 * 10 = 40
6 * 1 = 6
To get the number of digits in user entered value, you can get the value and check the length of the value after converting it to String. This will give you the exact length of the digit.
For example, if variable "uservalue" in the below snippet is user entered value, the output after executing the snippet, it prints the numberOfDigit as"3".
public static void main (String args[]){
int uservalue=546;
int numberOfDigit=0;
String userValueinStr=String.valueOf(uservalue);
numberOfDigit=userValueinStr.length();
System.out.println("Number of digits in user entered value is::"+numberOfDigit );
//Now as you got the no. of digits, you can go ahead and add the your logic of multiplication
}
int n = 546;
int exponent = (int) (Math.log10(n));
for (int i = exponent; i >= 0; i--) {
int displayNum = (n / (int) Math.pow(10, i)) * (int) Math.pow(10, i);
System.out.println(displayNum);
n = n - displayNum;
}
outputs
System.out﹕ 500
System.out﹕ 40
System.out﹕ 6

Why does this statement print this output?

Why does this print statement print 3 and not 1004 as the output?
int n = 2005;
for (int i = 0; i < 50; i++)
n = (n + 3) / 2;
System.out.print(n);
if I do this:
int n = 2005;
for (int i = 0; i < 50; i++)
System.out.println(n);
n = (n + 3) / 2;
System.out.print(n);
It prints 2005 for each iteration and 1004, for the last time.
If there was brackets (like below)
int n = 2005;
for (int i = 0; i < 50; i++){
System.out.println(n);
n = (n + 3) / 2;
}
System.out.print(n);
}
then it behaves like 2005
1004
503
253
128
65
34
18
10
6
4
3
3....3
Print n inside the for loop then you will got how this work.
int n = 2005;
for (int i = 0; i < 50; i++){
System.out.println(n);
n = (n + 3) / 2;
}
Without going into detail: You are more or less cutting n in half every time. Eventually n will approach 3. Then its (3 + 3) / 2 == 3. In fact, you would get there for most initial numbers given a long enough iteration.

find the sum of the multiples of 3 and 5 below 1000

Ok guys, so I'm doing the Project Euler challenges and I can't believe I'm stuck on the first challenge. I really can't see why I'm getting the wrong answer despite my code looking functional:
import java.util.ArrayList;
public class Multithree {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Integer> x = new ArrayList<Integer>();
ArrayList<Integer> y = new ArrayList<Integer>();
int totalforthree = 0;
int totalforfive = 0;
int total =0;
for(int temp =0; temp < 1000 ; temp++){
if(temp % 3 == 0){
x.add(temp);
totalforthree += temp;
}
}
for(int temp =0; temp < 1000 ; temp++){
if(temp % 5 == 0){
y.add(temp);
totalforfive += temp;
}
}
total = totalforfive + totalforthree;
System.out.println("The multiples of 3 or 5 up to 1000 are: " +total);
}
}
I'm getting the answer as 266333 and it says it's wrong...
you should use the same for loop for both to aviod double counting numbers that are multiple of both. such as 15,30...
for(int temp =0; temp < 1000 ; temp++){
if(temp % 3 == 0){
x.add(temp);
totalforthree += temp;
}else if(temp % 5 == 0){
y.add(temp);
totalforfive += temp;
}
}
In a mathematical perspective,
You did not consider about common factors between 3 and 5.Because there is double counting.
ex; number 15 ,
30 ,
45 ,
60 ,
75 ,
90 ,
105 ,
120 ,
135 ,
150 ,
165 ,
180 ,
195 ,
210 ,
225 ,
240 ,
255 ,
270 ,
285 ,
300 ,
315 ,
330 ,
345 ,
360 ,
375 ,
390 ,
405 ,
420 ,
435 ,
450 ,
465 ,
480 ,
495 ,
510 ,
525 ,
540 ,
555 ,
570 ,
585 ,
600 ,
615 ,
630 ,
645 ,
660 ,
675 ,
690 ,
705 ,
720 ,
735 ,
750 ,
765 ,
780 ,
795 ,
810 ,
825 ,
840 ,
855 ,
870 ,
885 ,
900 ,
915 ,
930 ,
945 ,
960 ,
975 ,
990 , are common factors.
total of common factors = 33165.
Your answer is 266333
Correct answer is 233168.
Your Answer - Total of common factors
266333-33165=233168.
(this is a code for getting common factors and Total of common factors )
public static void main(String[] args) {
System.out.println("The sum of the Common Factors : " + getCommonFactorSum());
}
private static int getCommonFactorSum() {
int sum = 0;
for (int i = 1; i < 1000; i++) {
if (i % 3 == 0 && i % 5 == 0) {
sum += i;
System.out.println(i);
}
}
Don't you all think instead of using loops to compute the sum of multiples, we can easily compute sum of n terms using a simple formula of Arithmetic Progression to compute sum of n terms.
I evaluated results on both using loop and formula. Loops works simply valuable to short data ranges. But when the data ranges grows more than 1010 program takes more than hours to process the result with loops. But the same evaluates the result in milliseconds when using a simple formula of Arithmetic Progression.
What we really need to do is:
Algorithm :
Compute the sum of multiples of 3 and add to sum.
Compute the sum of multiples of 5 and add to sum.
Compute the sum of multiples of 3*5 = 15 and subtract from sum.
Here is code snippet in java from my blog post CodeForWin - Project Euler 1: Multiples of 3 and 5
n--; //Since we need to compute the sum less than n.
//Check if n is more than or equal to 3 then compute sum of all divisible by
//3 and add to sum.
if(n>=3) {
totalElements = n/3;
sum += (totalElements * ( 3 + totalElements*3)) / 2;
}
//Check if n is more than or equal to 5 then compute sum of all elements
//divisible by 5 and add to sum.
if(n >= 5) {
totalElements = n/5;
sum += (totalElements * (5 + totalElements * 5)) / 2;
}
//Check if n is more than or equal to 15 then compute sum of all elements
//divisible by 15 and subtract from sum.
if(n >= 15) {
totalElements = n/15;
sum -= (totalElements * (15 + totalElements * 15)) / 2;
}
System.out.println(sum);
If you are using Java 8 you can do it in the following way:
Integer sum = IntStream.range(1, 1000) // create range
.filter(i -> i % 3 == 0 || i % 5 == 0) // filter out
.sum(); // output: 233168
To count the numbers which are divisible by both 3 and 5 twice you can
either write the above line twice or .map() the 2 * i values:
Integer sum = IntStream.range(1, 1000)
.filter(i -> i % 3 == 0 || i % 5 == 0)
.map(i -> i % 3 == 0 && i % 5 == 0 ? 2 * i : i)
.sum(); // output: 266333
How I solved this is that I took an integer value (initialized to zero) and kept on adding the incremented value of i, if its modulo with 3 or 5 gives me zero.
private static int getSum() {
int sum = 0;
for (int i = 1; i < 1000; i++) {
if (i % 3 == 0 || i % 5 == 0) {
sum += i;
}
}
return sum;
}
I did this several ways and several times. The fastest, cleanest and simplest way to complete the required code for Java is this:
public class MultiplesOf3And5 {
public static void main(String[] args){
System.out.println("The sum of the multiples of 3 and 5 is: " + getSum());
}
private static int getSum() {
int sum = 0;
for (int i = 1; i < 1000; i++) {
if (i % 3 == 0 || i % 5 == 0) {
sum += i;
}
}
return sum;
}
If anyone has a suggestion to get it down to fewer lines of code, please let me know your solution. I'm new to programming.
int count = 0;
for (int i = 1; i <= 1000 / 3; i++)
{
count = count + (i * 3);
if (i < 1000 / 5 && !(i % 3 == 0))
{
count = count + (i * 5);
}
}
Others have already pointed out the mistakes in your code, however I want to add that the modulus operator solution is not the most efficient.
A faster implementation would be something like this:
int multiply3_5(int max)
{
int i, x3 = 0, x5 = 0, x15 = 0;
for(i = 3; i < max; i+=3) x3 += i; // Store all multiples of 3
for(i = 5; i < max; i+=5) x5 += i; // Store all multiples of 5
for(i = 15; i < max; i+=15) x15 += i; // Store all multiples 15;
return x3+x5-x15;
}
In this solution I had to take out multiples of 15 because, 3 and 5 have 15 as multiple so on the second loop it will add multiples of 15 that already been added in the first loop;
Solution with a time complexity of O(1)
Another even better solution (with a time complexity of O(1)) is if you take a mathematical approach.
You are trying to sum all numbers like this 3 + 6 + 9 ... 1000 and 5 + 10 + 15 +20 + ... 1000 this is the same of having 3 * (1 + 2 + 3 + 4 + … + 333) and 5 * ( 1 + 2 + 3 + 4 + ... + 200), the sum of 'n' natural number is (n * (n + 1)) (source) so you can calculate in a constant time, as it follows:
int multiply3_5(int max)
{
int x3 = (max - 1) / 3;
int x5 = (max - 1) / 5;
int x15 = (max - 1) / 15;
int sn3 = (x3 * (x3 + 1)) / 2;
int sn5 = (x5 * (x5 + 1)) / 2;
int sn15 = (x15 * (x15 + 1)) / 2;
return (3*sn3) + (5 *sn5) - (15*sn15);
}
Running Example:
public class SumMultiples2And5 {
public static int multiply3_5_complexityN(int max){
int i, x3 = 0, x5 = 0, x15 = 0;
for(i = 3; i < max; i+=3) x3 += i; // Store all multiples of 3
for(i = 5; i < max; i+=5) x5 += i; // Store all multiples of 5
for(i = 15; i < max; i+=15) x15 += i; // Store all multiples 15;
return x3 + x5 - x15;
}
public static int multiply3_5_constant(int max){
int x3 = (max - 1) / 3;
int x5 = (max - 1) / 5;
int x15 = (max - 1) / 15;
int sn3 = (x3 * (x3 + 1)) / 2;
int sn5 = (x5 * (x5 + 1)) / 2;
int sn15 = (x15 * (x15 + 1)) / 2;
return (3*sn3) + (5 *sn5) - (15*sn15);
}
public static void main(String[] args) {
System.out.println(multiply3_5_complexityN(1000));
System.out.println(multiply3_5_constant(1000));
}
}
Output:
233168
233168
Just simply
public class Main
{
public static void main(String[] args) {
int sum=0;
for(int i=1;i<1000;i++){
if(i%3==0 || i%5==0){
sum+=i;
}
}
System.out.println(sum);
}
}
You are counting some numbers twice. What you have to do is add inside one for loop, and use an if-else statement where if you find multiples of 3, you do not count them in 5 as well.
if(temp % 3 == 0){
x.add(temp);
totalforthree += temp;
} else if(temp % 5 == 0){
y.add(temp);
totalforfive += temp;
}
Logics given above are showing wrong answer, because multiples of 3 & 5 are taken for calculation. There is something being missed in above logic, i.e., 15, 30, 45, 60... are the multiple of 3 and also multiple of 5. then we need to ignore such while adding.
public static void main(String[] args) {
int Sum=0, i=0, j=0;
for(i=0;i<=1000;i++)
if (i%3==0 && i<=999)
Sum=Sum+i;
for(j=0;j<=1000;j++)
if (j%5==0 && j<1000 && j*5%3!=0)
Sum=Sum+j;
System.out.println("The Sum is "+Sum);
}
Okay, so this isn't the best looking code, but it get's the job done.
public class Multiples {
public static void main(String[]args) {
int firstNumber = 3;
int secondNumber = 5;
ArrayList<Integer> numberToCheck = new ArrayList<Integer>();
ArrayList<Integer> multiples = new ArrayList<Integer>();
int sumOfMultiples = 0;
for (int i = 0; i < 1000; i++) {
numberToCheck.add(i);
if (numberToCheck.get(i) % firstNumber == 0 || numberToCheck.get(i) % secondNumber == 0) {
multiples.add(numberToCheck.get(i));
}
}
for (int i=0; i<multiples.size(); i++) {
sumOfMultiples += multiples.get(i);
}
System.out.println(multiples);
System.out.println("Sum Of Multiples: " + sumOfMultiples);
}
}
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t>0){
int sum = 0;
int count =0;
int n = sc.nextInt();
n--;
System.out.println((n/3*(6+(n/3-1)*3))/2 + (n/5*(10+(n/5-1)*5))/2 - (n/15*(30+(n/15-1)*15))/2);
t--;
}
}
}
If number is 10 then multiple of 3 is 3,6,9 and multiple of 5 is 5,10 total sum is 33 and program gives same answer:
package com.parag;
/*
* #author Parag Satav
*/
public class MultipleAddition {
/**
* #param args
*/
public static void main( final String[] args ) {
// TODO Auto-generated method stub
ArrayList<Integer> x = new ArrayList<Integer>();
ArrayList<Integer> y = new ArrayList<Integer>();
int totalforthree = 0;
int totalforfive = 0;
int number = 8;
int total = 0;
for ( int temp = 1; temp <= number; temp++ ) {
if ( temp % 3 == 0 ) {
x.add( temp );
totalforthree += temp;
}
else if ( temp % 5 == 0 ) {
y.add( temp );
totalforfive += temp;
}
}
total = totalforfive + totalforthree;
System.out.println( "multiples of 3 : " + x );
System.out.println( "multiples of 5 : " + y );
System.out.println( "The multiples of 3 or 5 up to " + number + " are: " + total );
}
}

Categories

Resources