Solving elimination using nested loops in java? - java

I was trying to solve a program challenge that solves this prompt
"When 2, 3, 4, 5, 6 eggs are removed at a time from a basket of eggs, the remaining amounts are 1, 2, 3, 4,5 eggs respectively. When 7 eggs are removed at a time, no eggs remain. What is the least number of eggs I could have had in the basket?"
I tried to make a program using nested loops and I feel like it should work, but when I run the program, it just prints blank space. I never get a number to satisfy the equation. Can someone help me, or show me what I did wrong please?
I'm only allowed to use nested loops and decision statements.
public class Program{
public static void main (String []args){
int c,d,e,f,g,h;
for (int j=1; j<1000; j++){
for (c=j; c>=1; c=c-2){
}
if (c==1){
for (d=j; d>=2; d=d-3){
}
if (d==2){
for (e=j; e>=3; e=e-4){
}
if (e==3){
for (f=j; f>=4; f=f-5){
}
if (f==4){
for (g=j; g>=5; g=g-6){
}
if (g==5){
for (h=j; g>=0; h=h-7){
}
if (h==0){
System.out.println(+j);
}
}
}
}
}
}
}
}
}

Try this:
public static void main(String[] args) {
int x = 7;
int result = -1;
while (true) {
if ((x % 2 == 1) && (x % 3 == 2) && (x % 4 == 3) && (x % 5 == 4)
&& (x % 6 == 5)) {
result = x;
break;
}
x += 7; // This because you know its multiple of 7
}
System.out.println("Result is: " + result);
}

int numberOfEggs = 0;
for (;;)
{
if (numberOfEggs % 2 == 1 &&
numberOfEggs % 3 == 2 &&
numberOfEggs % 4 == 3 &&
numberOfEggs % 5 == 4 &&
numberOfEggs % 6 == 5 )
return numberOfEggs;
else
numberOfEggs += 7;
}

Related

Printing numbers 1-100, except when divisible by 5 or 12

The question is
Write a Java program that prints numbers from 1 to 100. If the number is divisible by 5, instead of printing the number, your program should print how many fives are in this number, if the number is divisible by 12 it should print how many twelves are in this number.
Here's my current attempt:
import acm.program.*;
public class FiveTwelve extends ConsoleProgram {
public void run() {
int a = (1);
int b = (5);
int c = (12);
for (a = 1; a <= 100; a++) {
println(a);
if ((a % 5) == 0) {
println(a/b);
} else if ((a % 12) == 0) {
println(a / c);
}
}
}
}
The problem is that my code is also printing the divisible number instead of just the outcome. Example output:
1
2
3
4
5
1
6
7
8
9
10
2
11
12
1
This goes on. I want to remove numbers that are divisible by 5 and 12. Instead, I need to show the result or num/5 && num/12.
UPDATE!!!
import acm.program.*;
public class FiveTwelve Extends ConsoleProgram{
public void run() {
for (int a = 1; a <= 100; a++) {
if (a % 5 == 0 && a % 12 == 0) {
println(a / 5);
println(a / 12);
} else if (a % 5 == 0) {
println(a / 5);
} else if (a % 12 == 0) {
println(a / 12);
} else {
println(a);
}
}
}
}
guess we all missed something.
Instead of solving for the specific case, let's write an extensible solution. First, what variables are there in the question that could change? I'd say they are:
The starting number 1
The last number 100
The divisors 5 and 12
Additionally, as #Anoml pointed out, the problem wording suggests that if your number is divisible by multiple divisors, we should print out the number of times it is divisible for every applicable divisor. And, as you noted in your question, we only want to print the number itself when it is not divisible by any divisors.
So, our solution becomes:
import acm.program.*;
public class FiveTwelve extends ConsoleProgram {
private final int FIRST = 1;
private final int LAST = 100;
private final int[] DIVISORS = { 5, 12 };
public void run() {
boolean hasDivisor;
for (int i = FIRST; i <= LAST; i++) {
hasDivisor = false;
for (int divisor : DIVISORS) {
if (i % divisor == 0) {
println(i / divisor);
hasDivisor = true;
}
}
if (!hasDivisor) {
println(i);
}
}
}
}
This way, we can change our starting number, last number, or which divisors we support, and the program will still pass.
This is what you intended to do, println(a) in all other cases.
for (int a = 1; a <= 100; a++) {
if (a % 5 == 0) {
println(a / 5);
} else if (a % 12 == 0) {
println(a / 12);
} else {
println(a);
}
}

(Java) need help finding 20 greatest and 20 smallest numbers

I've already found all of the numbers from 1- 9876543210 that are divisible by 1-10 through the for and if statements but I can't seem to figure out how to find the largest and the smallest numbers. Please if you do help me, explain how you did it and the logic behind it.
long bignumber = 9876543210L;
for (int i = 0; i < bignumber; i++) {
if (i % 1 == 0) {
if (i % 2 == 0) {
if (i % 3 == 0) {
if (i % 4 == 0) {
if (i % 5 == 0) {
if (i % 6 == 0) {
if (i % 7 == 0) {
if (i % 8 == 0) {
if (i % 9 == 0) {
}
}
else {
}
}
else {
}
}
else {
}
}
else {
}
}
else {
}
}
else {
}
}
else {
}
}
else {
}
}
else {
}
}
I don't want to write your code for you, but here are some hints.
Firstly, i should be of type long because otherwise it's an infinite loop. Every int value is less than 9876543210L. That's why you used long in the first place.
Secondly, I recommend learning about the && operator. This can be used instead of nested if statements.
Thirdly, if you only need the 20 smallest values and the 20 largest, you could use 2 loops. The first should loop through the numbers in ascending order and break when 20 values have been found. The second should loop through the values in descending order and break when 20 have been found.

Method using recursion causing code to fail at run time, involves global variable

This question is poorly worded, but how do I make my code run as desired without getting about a hundred error messages at run time when I use recursion? This is my faulty program
public class Collatz
{
public static int count;
public static int pluscount() {
return count++;
}
public static void collatz (int n)
{
if (n < count) {
System.out.print(n + "");
}
if (n == 1) return;
if (n % 2 == 0) {
pluscount();
collatz(n / 2);
}
else {
pluscount();
collatz(3*n + 1);
}
}
public static void main(String[] args)
{
int N = Integer.parseInt(args[0]);
int[] array = new int [N+1];
for (int i = 0; i <= N; i++) {
count = 0;
collatz(i);
array [i] = count;
}
int max = StdStats.max(array);
System.out.println(max);
}
}
If I change the collatz() method to
public static void collatz (int n)
{
count ++;
StdOut.print(n + "");
if (n == 1 || n == 0) return;
if (n % 2 == 0) collatz(n / 2);
else
collatz(3*n + 1);
}
and remove the pluscount() from my code, and input 7 as the argument, the code runs and prints 01213105168421421516842163105168421722113417522613402010516842117
175226134020105168421, but it's supposed to print 7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
Here are the instructions from my Java textbook if anyone doesn't understand what I'm trying to accomplish:
Consider the following recursive function, which is related to a famous unsolved problem in number theory, known as the Collatz problem or the 3n + 1 problem.
public static void collatz(int n) {
System.out.print(n + " ");
if (n == 1) return;
if (n % 2 == 0) collatz(n / 2);
else collatz(3*n + 1);
}
For example, a call to collatz(7) prints the sequence
7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
as a consequence of 17 recursive calls. Write a program that takes a command-line argument N and returns the value of n < N for which the number of recursive calls for collatz(n) is maximized.
There are two problem with your code
1.For loop in main method starts with 0 which causes problem.Start iterating from 1
for (int i = 1; i <= N; i++)
2.No need to put if (n < count) in collatz method
When you call collatz(i) and get the result, I would not save it to an array. Instead just keep track of you max count and your max n. Something like this should do the trick based on the approach you are going:
public static int count;
public static void collatz(int n) {
count++;
//System.out.print(n + " ");
if (n == 1) return;
if (n % 2 == 0) collatz(n / 2);
else collatz(3*n + 1);
}
public static void main(String[] args)
{
int N = Integer.parseInt(args[0]);
int maxn = 0;
int maxCount = 0;
for (int i=1; i<=N; i++){ //Start at 1 since collatz(0) is infinite
count = 0;
collatz(i);
if (count>maxCount){
maxCount = count;
maxn = i;
}
}
System.out.println("your max n is: "+maxn);
}
Also notice that I commented out the print statment in collatz. The problem just focuses on how many recursion calls are being made. We do not really care what the output is during all of the recursion calls.
Hope this helps.

Why do I get wrong output?

I am very new to Java and am trying to write a simple code. Here is the description:
Write a program that prompts the user for a number X. Print the
numbers from 1 to X. However, in place of multiples of 4 print “qqqq”. In place of multiples of 7, print “seven”. If a number is divisible by both 4 and 7 print “qqqqseven”. It means if I input 4, my output should be 1, 2, 3, (qqqq), ...but I get 1(qqqq), 2(qqqq), 3(qqqq), 4(qqqq)..... Can anyone help me and let me know where I am doing wrong? Any help is appreciated. Than you.
public static void main(String args[])
{
//Print Method
System.out.println("Enter number upto which you want to print: ");
Scanner input = new Scanner(System.in);
int x;
x = input.nextInt();
for(int i=1; i <= x; i++)
{
System.out.println(i);
//if x is multiples of 4
if (x % 4 == 0)
System.out.println("qqqq");
//if x is multiples of 7
if (x % 7 == 0)
System.out.println("seven");
//if x is divisible by 4 and 7
if (x % 4 == 0 && x % 7 == 0)
System.out.println("qqqqseven");
}
}
}
Replace
if (x % 4 == 0)
With
if (i % 4 == 0)
Do likewise for the other occurrences of %
To get the correct output for multiple of 28 you will need to modify you code to this:
if (i % 4 == 0 && i % 7 == 0) { // if i is a multiple of 28 (of both 4 & 7)
System.out.println("qqqqseven");
}
else {
if (i % 4 == 0) { // if i is multiples of 4
System.out.println("qqqq");
}
else if (i % 7 == 0) { // if i is multiples of 7
System.out.println("seven");
}
}
The idea here is to use the if condition from most specific to least specific. In you case the most specific condition is a divisor of 4 and 7, followed by divisor of 4, divisor fo 7 and finally the least specific one which means everything else. If you could arrage your if conditions in that order you'll get the result.
Note: It a good practice to close scanner or any resources that you open. :)
import java.util.Scanner;
public class TestProgram {
public static void main(String[] args) {
System.out.println("Enter number upto which you want to print: ");
Scanner input = new Scanner(System.in);
int x;
x = input.nextInt();
for (int i = 1; i <= x; i++) {
if(i%4 == 0 && i%7 == 0) {
System.out.println("qqqqseven");
} else if(i%4 == 0) {
System.out.println("qqqq");
} else if(i%7 == 0){
System.out.println("seven");
} else {
System.out.println(i);
}
}
input.close();
}
}

Project Euler #5(Smallest positive number divisible by all numbers from 1 to 20): Ways to Optimize? ~Java

Problem 5: 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
I have solved the problem 5 of Project Euler
Here is the Java code:
static long FindLcm(long a,long b)
{
long lcm,hcf = 0;
long i=1;
long ger=a>b?a:b;
while(i<ger)
{
if((a%i==0) && (b%i==0))
hcf=i;
i++;
}
lcm=(a*b)/hcf;
return lcm;
}
static void FindMultiple()
{
long lcm=1;
for(long i=2;i<=20;i++)
{
lcm=FindLcm(lcm,i);
}
System.out.println("Lcm="+lcm);
}
How can optimize this?
Your FindMultiple() method is not bad,
static void FindMultiple()
{
long lcm=1;
for(long i=2;i<=20;i++)
{
lcm=FindLcm(lcm,i);
}
System.out.println("Lcm="+lcm);
}
it implements a fairly good algorithm. Your problem is that your FindLcm() contains a nasty performance bug.
static long FindLcm(long a,long b)
{
long lcm,hcf = 0;
long i=1;
// This sets ger to max(a,b) - why?
long ger=a>b?a:b;
// This would return a wrong result if a == b
// that never happens here, though
while(i<ger)
{
if((a%i==0) && (b%i==0))
hcf=i;
i++;
}
lcm=(a*b)/hcf;
return lcm;
}
You are looping until you reach the larger of the two arguments. Since the cumulative LCMs grow rather fast, that takes a lot of time. But the GCD (or HCF, if you prefer) of two (positive) numbers cannot be larger than the smaller of the two. So looping only until the smaller of the two arguments is reached makes the number of iterations at most 20 here, do that 19 times (for i = 2, ..., 20), it's a trivial amount of computation.
Changing to
long ger = a < b ? a : b;
while(i <= ger) {
gives me (adding timing code, not measuring the printing):
17705 nanoseconds
Lcm=232792560
So less than 20 microseconds for the computation. We can easily push that below 6 microseconds if we use the euclidean algorithm to find the greatest common divisor,
static long gcd(long a, long b) {
while(b > 0) {
a %= b;
if (a == 0) return b;
b %= a;
}
return a;
}
and below 5 if we directly use the GCD as
lcm *= i/gcd(lcm,i);
in FindMultiple().
You're solution is more or less brute force which is why it's taking so long. We know that 2520 is the lcm of (1,2,...,9,10) which means two useful things: 1.) We can start checking factors at 11 and 2.) The answer is a multiple of 2520.
You're searching for the Greatest Common Divisor (gcd) of the answer and the next number in your sequence (similar to a bubble sort). You could just check to see if your current answer is divisible by the next factor and if not then add your current answer to itself until the answer is divisible by the next factor. For Example:
static long findLCM(long a, long b) {
long lcm = (a>b) ? a : b;
while (lcm % b != 0) {
lcm += a;
}
return lcm;
}
Since we started with lcm = a, we know that as long as we add a's to lcm then lcm will always be divisible by a. Now, we just need to make some multiple of a divisible by b. This process should cut out many steps of first finding the gcd as well as iterating from 2 through 10.
i did it like this, which was the easiest way i could think of. it's also a little faster than yours.
for(int i = 190; ; i += 190) {
if(i % 3 == 0
&& i % 4 == 0
&& i % 6 == 0
&& i % 7 == 0
&& i % 8 == 0
&& i % 9 == 0
&& i % 11 == 0
&& i % 12 == 0
&& i % 13 == 0
&& i % 14 == 0
&& i % 15 == 0
&& i % 16 == 0
&& i % 17 == 0
&& i % 18 == 0
&& i % 20 == 0) {
System.out.println(i);
break;
}
}
Here are 4 different methods to obtain the result (4 different ways to obtain GCD) + the total time. All of them are based on the following observation:
a*b
lcm(a,b) = ----------
gcd(a,b)
where:
LCM = Least Common Multiple
GCD = Greatest Common Divisor
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
public class A {
final static int N = 20;
static Map<Integer, String> messages = new HashMap<>();
static {
messages.put(0, "Euler - difference");
messages.put(1, "modulo - recursive");
messages.put(2, "modulo - iterative");
messages.put(3, "BigInteger implementation");
}
private static long GCD0(long x, long y) {
while (x != y) {
if (x > y) {
x -= y;
} else {
y -= x;
}
}
return x;
}
private static long GCD1(long x, long y) {
if (x % y == 0) {
return y;
}
return GCD1(y, x % y);
}
private static long GCD2(long x, long y) {
long aux;
while (x % y != 0) {
aux = y;
y = x % y;
x = aux;
}
return y;
}
private static long GCD3(long x, long y) {
BigInteger xx = BigInteger.valueOf(x);
BigInteger yy = BigInteger.valueOf(y);
return xx.gcd(yy).longValue();
}
private static void doIt(int pos) throws Exception {
System.out.print("\n" + messages.get(pos));
printSpaces(25, messages.get(pos).length());
Class cls = Class.forName("A");
Object obj = cls.newInstance();
Method method = cls.getDeclaredMethod("GCD" + pos, long.class,
long.class);
long start = System.nanoTime();
long p = 1;
for (int i = 2; i <= N; i++) {
p = (p * i) / (long) method.invoke(obj, p, i);
}
long stop = System.nanoTime();
System.out.println("\tTime: " + (stop - start) / 1000 + " microseconds");
System.out.println(p);
}
private static void printSpaces(int total, int actualLength) {
for (int i = 0; i < total - actualLength; i++) {
System.out.print(" ");
}
}
public static void main(String[] args) throws Exception {
doIt(0);
doIt(1);
doIt(2);
doIt(3);
}
}
Output:
Euler - difference Time: 137205 microseconds
232792560
modulo - recursive Time: 1240 microseconds
232792560
modulo - iterative Time: 1228 microseconds
232792560
BigInteger implementation Time: 2984 microseconds
232792560
P.S.: I used reflection to call those methods easier, but you can call the method directly to obtain a better performance + a better readability.
int i = 20;
while (true)
{
if (
(i % 1 == 0) &&
(i % 2 == 0) &&
(i % 3 == 0) &&
(i % 5 == 0) &&
(i % 7 == 0) &&
(i % 9 == 0) &&
(i % 11 == 0) &&
(i % 13 == 0) &&
(i % 16 == 0) &&
(i % 17 == 0) &&
(i % 19 == 0) )
{
break;
}
i += 20;
}
S.O.P(i);
C++ Program with minimum iteration... very much resemble to Daniel Fischer
#include<iostream>
using namespace std;
int main()
{
int num = 20;
long lcm = 1L;
for (int i = 2; i <= num; i++)
{
int hcf = 1;
for (int j = 2; j <= i; j++)
{
if (i % j == 0 && lcm % j == 0)
{
hcf = j;
}
}
lcm = (lcm * i) / hcf;
}
cout << lcm << "\n";
}
This method uses brute force, but skips as soon as a number fails instead of continuing to compare the remainders. Heck, it never checks for 20 unless 19 has passed already, which actually makes it pretty efficient.
#include<stdio.h>
int a = 1, b = 1, rem;
int main() {
while (b < 20){
rem = a % b;
if (rem != 0){
a++;
b = 1;
}
b++;
}
printf("%d is the smallest positive number divisible by all of the numbers from 1 to 20.", a);
}
A Non Brute Force Method
This one is instantaneous! Doesn't even take a second. Run the code to understand the logic. It's written in C
#include <stdio.h>
int main() {
int primes[8]={2,3,5,7,11,13,17,19};
int primes_count[8]={0,0,0,0,0,0,0,0};
int i,j,num,prime_point;
int largest_num=1;
printf("\nNUM");
for(j=0;j<8;j++)
printf("\t%d",primes[j]);
for(i=2;i<=20;i++) {
num=i;
int primes_count_temp[8]={0,0,0,0,0,0,0,0};
for(j=0;j<8;j++) {
while(num%primes[j]==0) {
num=num/primes[j];
primes_count_temp[j]++;
}
}
for(j=0;j<8;j++)
if(primes_count_temp[j]>primes_count[j])
primes_count[j]=primes_count_temp[j];
printf("\n %d",i);
for(j=0;j<8;j++)
printf("\t %d",primes_count_temp[j]);
}
printf("\nNET");
for(j=0;j<8;j++)
printf("\t%d",primes_count[j]);
printf("\n");
for(i=0;i<8;i++)
while(primes_count[i]) {
largest_num*=primes[i];
primes_count[i]--;
}
printf("The answer is %d \n",largest_num);
return 0;
}
Now if a number is divisible by X it will be divisible by its prime factors also. So if a number is divisible by 20 it will be divisible by its prime factors. And there are 8 prime factors under 20. I take each number under 20 and find its prime factors, also see the power of the prime factor and keep a count of the highest power.
Once you're done. Multiply all the prime factors raised to their highest power.
my Solution for this in python. this is so simple and use pure Math rules
get the Least Common Multiple
def getLCM (x, y):
return x*y/getGCD(x,y)
get the Greatest Common Divisor
def getGCD(a,b):
while(True):
if(a%b != 0):
temp = b
b = a%b
a = temp
else:
return b
break
Find the Least Common Multiple of, LCM of prev two numbers and next number in list.
LCM(LCM of prev two numbers,next number in list)
num_list = list(range(1,21))
finalLCM = 1
for i in num_list:
finalLCM = getLCM(finalLCM,i)
print(finalLCM)
Full Python Code
def getLCM (x, y):
return x*y/getGCD(x,y)
def getGCD(a,b):
while(True):
if(a%b != 0):
temp = b
b = a%b
a = temp
else:
return b
break
num_list = list(range(1,21))
finalLCM = 1
for i in num_list:
finalLCM = getLCM(finalLCM,i)
print(finalLCM)
we have create an array which was common divisible eg: if any number is divisible by 20 then no need to divisible by 2,4,5,10
<?php
$chk=20;
$div=array(11,12,13,14,15,16,17,18,19,20);
for($number=1;1;$number++){
$chk=$number;
foreach($div as $value){
if($number%$value!=0){
$chk=0;
$number+=$value;
break;
}
}
if($chk!=0){break;}
}
echo $chk;
?>

Categories

Resources