## Logic and Loops Practice Comments

• #### /users/1550

Haha, LOL! I can't solve it now, it's funny! But I solve the problem some other way, I created my own version of code with another logic:

import java.util.Scanner;

• #### Amboss

there some kind of mistake? Method contain two params, why does it can calculating with only one param?????

• #### David

if a and b are the same, then its essentially one parameter. (a+b) * 2 is the same as a * 4

• #### Krondo

Really simple stuff. For those of you stuck on this, remember order of operations and == other than that this should be a piece of cake with some ice cream.

• #### Cherry Chen

I copied the answer in and it was still incorrect... what dafuq this site has bugs and it's teaching me how to code? what is this.

``````if(a==b){
return a * 4;
}
else{
return a+b;
}
``````
• #### Learneroo

@Cherry, you left out the closing curly bracket of the method when you copied the code.

The problem is with the last set of parameters. It is 2 and 2 and expects an 8, when in fact it should expect a 4.

• #### chima oscar

Very interesting. I went further to add an extra if statement that allows only numbers between 1 and 6.

• #### TJ Duarte

here's mine :

import java.util.Scanner;

public class Main {

``````static int doStuff(int a, int b){
if(a!=b)
{
return a+b;
}
else
{
return (a+b)+(a+b);
}
}
``````

I do it. It was interesting.

• #### Mony Jang

Please can someone help. I can't figure out what I'm doing wrong in this question.
Here is my code
import java.util.Scanner;

public class DiceRolling {

• #### sumo

this is so simple...use the same logic as you used in earlier challange of if else.....
ie;
if (a==b){
return (a+b)*2;
}else
return (a+b);
}

• #### Janusz

Random rand = new Random();

``````    int a = rand.nextInt(7);
int b = rand.nextInt(7);
``````
• #### ddds

check the logic this is correct one :
if(a==b){
return (a+b)+(a+b);
}
else{
return a+b;
}

• #### Dixit

showing error

• #### Dheeraj Parmar

#include
using namespace std;

int func(int a , int b){
int sum=a+b;
if(a != b){
return sum;

``````}
else if(a == b){
return sum*2;
}
return 0;
``````

}
int main(){
int a=0;
int b=0;
cin>>a>>b;
cout<<func(a,b);

}

• #### Roger

let a = 0 + Math.floor(Math.random()* 6) + 1;
let b = 0 + Math.floor(Math.random()* 6) + 1;

function diceRoll() {
let sum = a + b;
if (a == b) {
return sum *= 2
} else {
return sum
}
}

• #### Victoria Holland

An interesting thing I discovered in this task is that you can't use return statements within a switch-block otherwise the compiler will say the break statements are unreachable. I had to assign

• #### Learneroo

@Victoria, thanks. If you use a return statement, you should remove the `break` after it, since return exits the block of code. To help avoid errors, the Java compiler doesn't accept code it recognizes as unreachable (even if just a `break` statement).

• #### Dino Šišić

You can make an String array and a new String after which you can do the following if for example num == 1 then assign the value of array[0] which is "one" in which case the new String equals "one". For too large and too small assign the "too large" or "too small" string from array if num < 1 and if num > 4 assign those strings from array to new String. Close all if and else if statements and return the new String.

• #### alan

Is there an easier way to do this? For the numbers 1-4 and other conditions, i made an individual if statement to save the string value to a variable. It seems kind of inefficient to write 6 if statements.

• #### Learneroo

@alan, you can use a switch case instead. Click on "Featured Answers" above the Hint.

• #### Bill

Need help
import java.util.Scanner;

public class Main {

``````public static String doStuff(int num){
for(int i = 1; i < 5; i++){
``````
• #### Budafai Gergely

My solution is:

String mes = "";
String[] onetofour = {"one", "two", "three", "four"};
for (int i =1; i<onetofour.length+1; i++) {
if (num== i) {

• #### Macro

``````public static String doStuff(int num){
String[] str = {"too small", "one", "two", "three", "four", "too large"};
if(num < 1){
return str[0];
}
else if(num > 4){
return str[5];
}else{
return str[num];
}
}
``````
• #### flowra

My solution and it is correct :
String result="";
String [] test = {"one","two","three","four"};
if (num 4) result= "too large";

• #### Bernard Mitchell

This continuation of "if" and "else" problems doesn't explain how to convert numbers to text. Can you please explain?

• #### Learneroo

You need to return a String.

• #### Bernard Mitchell

Can I get an explanation on how to return a string? Like I said this wasn't covered in previous lessons.

• #### Learneroo

Instead of `return 5;`, you do `return "hello";` See String Class for more info.

Thank You

• #### Bernard Mitchell

I keep getting errors in the code I didn't write and I haven't touched the boiler plate code.

import java.util.Scanner;

public class Main {

``````public static String doStuff(int num){
``````
• #### Bernard Mitchell

Never mind got it although I don't know if the way I did it is the most efficient. Thanks love this site!!!!

• #### thales

what is wrong with this code:

``````    String number;
switch(num){
case 1:
number= "one";
break;
case 2:
number= "two";
``````
• #### thales

this code works in eclips?

• #### thales

I think i have a very good queston ( at least i hope so).

Why isnt declaring enough en should i initialize the string. so
String message=""; works ( initializing)
String message; does not work, why not? for a string it does not mather right. i get it if it was an int but now??

• #### Mari Garchagudashvili

What is wrong with this code?

``````textDef = ["Too small","One","Two","Tree","Four","Too large"]
def printText (num):
if num<1:
print (textDef[0])
elif num>4:
print (textDef[5])
else:
print(textDef[num])

printText(2)
``````
• #### L

My solution

``````if(num < 1) return "too small";
if(num > 4) return "too large";

String[] words = {"one","two","three","four"};
return words[num-1];
``````

• #### Hanlise

def function1(a):
x=range (1, 5)
output=""
thisdict={
1:"One",
2:"Two",
3:"Three",
4:"Four"
}

• #### Roger

im not too comfortable with loops just yet but these are my 2 solutions on js:

/*function convert(a) {
let num = a
if (num < 1) {
return 'too small'

• #### Roger

const word = {
1: 'one',
2: 'two',
3: 'three',
};

function convert(i) {
let num = word[i]
if ( i < 1 || i > 3) {
return 'out of range'
} else {
return num
}
}

• #### David

LOL had to go back to Booleans chapter.... people Booleans is different from booleans, careful when defining your boolean.

• #### Jig

I tries using only booleans but didn't work for all conditions, the following worked for me.
if (gold>=pirates &&gold+pirates <100){
return true;
}
else{
return false;
}
}

• #### thales

I had the following it worked.

my code

my code

• #### L

My solution
return(!(gold+pirates > 100) && gold >= pirates);

Only this works.

``````return gold >= pirates && gold+pirates < 101;
``````
• #### Nouman Khalid

return gold+pirates>100?false:gold>=pirates?true:false;
works for me

• #### Hanlise

def function1(gold, pirates):
sum1=gold+pirates
if gold >= pirates and sum1 < 100:
return True
else:
return False

I use python

• #### Roger

function pirateShip(gold, pirates) {
let x = gold + pirates
if (x > 100) {
return 'ship sank'
} else if (gold >= pirates) {
return 'success'
} else {
return 'failed'
}
}

using js

• #### Michael

please fix If there's at least as much gold as pirates, that's good. it should if the gold is greater but cannot divided equal to pirates

• #### Dino Šišić

if someone is having trouble with inconpatible types (boolean/integer) pay attention to:

public static boolean doStuff(int gold, int pirates)

Hope it helps :)

• #### saeed

I am having big trouble with inconpatible types (boolean/integer);
even when I replace cheet answer...?!!?!

Main.java:7: error: incompatible types
return 0;
^
required: boolean
found: int

• #### Learneroo

@saeed, the header of your method should say `static int doStuff`, not `static boolean doStuff`

• #### Peter Fekete

"If there's at least as much gold as pirates, that's good (even though the gold cannot be divided equally)" this would produce 1 at the input 10 10

• #### Islam Elzohary

my code

``````             if (pirates > gold || pirates + gold > 100) return 0;
else if (gold%pirates == 0) return 2;
else return 1;
``````
• #### Nouman Khalid

return (gold100)?0:gold%pirates==0?2:1;

if you want to do it in one line

• #### Hanlise

def function1(gold, pirate):
sum1=gold+pirate
if sum1 < 100: #True
if gold > pirate and not gold % pirate == 0:
return 1
if gold % pirate == 0:
return 2
else:
return 0
else:
return 0

using python

• #### Rajat

gold = int(input("enter the value"))
pirates = int(input("enter the value"))
sum1 = gold+ pirates
if gold > pirates and not gold % pirates == 0:
return 1
elif gold % pirates == 0:

• #### Matt

Completed, but won't check off.

• #### Кирилл Варивода

Ha, I was just using this formula working only with int values:
x = (1000*15)/100

• #### David

Just gotta say that thanks for including quotes, it keeps me somewhat interested and inspired at the same time while going through this awesome noob training. Pura vida!

• #### isnard

``````int[] ar = {0,5,10,15,20,25};
return (a * ar[b])/100;
``````
• #### Shena

ahahaha :D i don't understand the instructions????
hmpff guess so ... i couldn't figure out why those are the outputs ... -.-
can someone explain the instructions ? hehehe :)

• #### Shena

ahhhh okey got it myself ehehe :D anyways thanks :)

• #### Bernard Mitchell

double f= b*.05; // .05, .1, .15, .2, .25
double c= a*f;
return (int)c;

• #### thales

If you just use doubles instead of integers then integers become doubles.
example 5/2=2 but 5/2.0=2.5

my code

• #### Islam Elzohary

I don't understand the proplem!!!

• #### Karina Nihalani

I don't understand the problem.

• #### Learneroo

You just need to calculate the tip according to the given table. The tip should be a percentage of the the total purchase. I added an example to make it clearer.

• #### Anand Ani

easy peoples
import java.util.Scanner;

public class Main {

``````static int doStuff(int a, int b){

switch(b)
{
case 1:
return (int)(a*0.05);
``````
• #### Hanlise

def do_stuff(a, b):
output=int()

thisdict={
1:0.05,
2:0.1,
3:0.15,
4:0.2,
5:0.25

}

output += thisdict.get(b)

x=a*output
return x

• #### Dheeraj Parmar

#include

using namespace std;

int func(int a , int b){

``````return a*(b*0.05);
``````

}
int main()
{

int a,b;
cin>>a; // no of purchase amount:
cin>>b; // the quality of service recieved:
cout<<func(a,b);

}

• #### AMR

Using Python - Do you guys think this code is too long and messy?

price_of_meal = float(input("How much did your meal cost: "))
quality_of_service = int(input("Rate the quality of service based from 1 to 5: "))

• #### Roger

const service = {
1: 0.05,
2: 0.1,
3: 0.15,
4: 0.2,
5: 0.25,
}

function qualityOfService(a, b) {
let tip = a * service[b]
return tip
};

• #### Roger

const service = {
1: 0.05,
2: 0.1,
3: 0.15,
4: 0.2,
5: 0.25,
}

function qualityOfService(a, b) {
let tip = a * service[b]
return tip += a
}
console.log(qualityOfService(10, 3).toFixed(2))

• #### thales

how can this be wrong?

• #### thales

solved it, it was just a bracket to much ( luckely not a bridge to far :-))

• #### Indrajith Karunarathne

Solved, It's really Easy.
static int doStuff(int a, int b){
int sum = a + b;
if (sum>21){
return 0;
}else{
return sum;
}
}

you can do it in a single line ex

return (a+b > 21)? 0 : a+b; // just like that.

• #### Hanlise

sum1= a+b
if sum1 > 21:
return 0
else:
return sum1

using python it should works

• #### Matt

Perfect, makes sense. Thanks!

• #### Кирилл Варивода

It's really simple but not boring, great!

• #### Eduardo Bonet

Bug on last entry with javascript for both BlackJack 1 and BlackJack 2: when read the last line I get "7 11", but after I use parseInt my function receives 7 and 1.

if 11 is converted to 1, last correct output is wrong.

• #### Learneroo

@Borja, it is only converted to 1 if it will otherwise overshoot 21.

Shame on me :) got totally focused on converting 11 to 1. Thanks for pointing out

• #### Cameron Guyer

Can't figure out how to convert the correct output to 13 and 14 with the correct code. Everything I tried does a compilation error.

• #### thales

Lets say i have 11 and 11. then automaticly it wil return 12. but perhaps i am a weird player of somekind and i want it to be 2. In the casino i can choose this if i want, here i cant?

my code

• #### ani2fun

why compilation fails error ? my code

• #### Prateek

if((a+b)<22 && a!=11 && b!=11){
return a+b;
}
if(a==11 || b==11){

``````            if((a+b)>21){
if(a==11)
a=1;
if(b==11)
b=1;
}

return a+b;
}

return 0;
``````
• #### Dharnish

very simple....
return a+b<21?a+b:(a==11||b==11)?a+b-10:0;

• #### vignesh

return a+b>21?(a==11?b+1:(b==11?a+1:0)):a+b;

• #### Roberto Blanco Axelsson

One way to do it:

int sum = a+b;
int one = 1;

``````    if(sum>21){

if(a == 11){
return one+b;
}
if(b == 11){
return one+a;
}
return 0;
}

return sum;
}
``````
• #### Hanlise

def do_stuff(a, b):
sum1=a+b
if a ==11:
a=1

``````if b == 11:
b=1

else:
return a+b
if sum1 > 21:
return 0
return a+b
``````

This is my code but it's weird. But I got 2 incorrect output

• #### Hongwen

For input set 5 3 19, we can get 19 using 3 pennies and 4 nickels. So it should be true there.

• #### Hongwen

Sorry, I mistook nickels and pennies...

• #### Amboss

5, 4, 23 will result false !!!!!! it ca't be true 5*5 +4 = 24 ?????????????????

• #### Learneroo

@Amboss, the challenge is to see if you can select the exact change from the coins you are given. So if you have 5 nickels, you can select 4 of them, add 4 pennies for a sum of 24 cents.

• #### Кирилл Варивода

I've made the code, but when I run table below shows that all cases are correct EXCEPT that "Your Output" is incorrect, it's red.
I don't know why, I checked some made up cases manually on Eclipse.

• #### Learneroo

Кирилл, When given 7 nickels and 3 pennies, can you get 35 cents? Yes, you just select the nickels and ignore the pennies. Check your code to see what it returns.

• #### Кирилл Варивода

Admin (?), I've make some changes, even few, but still, there is something wrong. Your example works, thanks for it!)
I'm just curious where I get lost.

• #### Learneroo

Кирилл. there's another example you're getting wrong. I think you should approach this problem a little differently. You can solve it with one if-else statement.

• #### Кирилл Варивода

You can solve it with one if-else statement.
You're right. And only now it's shows "Correct". I have to say that with no mathematical help I won't do that. So, on my opinion this problem more related to mathematics rather then to programming.

• #### David

OMG :( this took me forever also my code is extensive.... looks like complying with DRY is going to take me looong time to master.

• #### saeed

At the end of my program I write << return boolean; >> but program say error:

variable bool might not have been initialized
return bool;

• #### saeed

I found my solution;
when I defined boolean bool I must give amount to it LIKE boolean bool = false;

• #### Learneroo

I archived many comments here with solutions. You can link to your solution (in your submissions) to share it, but you shouldn't paste the whole solution in here.

• #### Shena

i'm confused i'm not familiar with nickel and pennies and cents -.- do they have relationships with each other ? like how many cents are there in pennies or in nickel ? :)

• #### Brayden Plush

American Currency^ LOL

• #### Calvin

For those of you in different countries: Pennies are 1 cent, Nickles are 5 cents (each).

• #### thales

I think i have a good solution? is it a smart solution?

my code

• #### Ravi

I wrote my code in python. it's working if i run this in some other compiler but here it's not.
my code

• #### Learneroo

Boilerplate code for this challenge wasn't provided for Python, so you need to take in the input yourself from STDIN.

• #### Lukas

``````    int nCount = sum / 5;
if (nCount <= nickels) {
return sum % 5 <= pennies;
} else {
return false;
}
``````
• #### Prateek

int a=sum/5;
int b=sum%5;
if(nickels>=a && pennies>=b){
return true;
}
return false;

• #### Charlotte

``````if ((sum%nickels) > pennies) return false;
return true;
``````

how the heck did this pass all the tests..

• #### Learneroo

Thanks, that's actually an edge case that wasn't covered before. The last test case will now check that condition so that code no longer passes.

• #### Amanpreet Singh

I did this way
if(nickels>=sum/5 && pennies>=sum%5)
{
return true;
}
else
{
return false;
}

• #### Kyle Lemon

Here's some working boilerplate for Ruby:

n = gets.chomp.to_i
n.times do
input = gets.chomp.split(" ").map(&:to_i)
nickels = input[0]
pennies = input[1]
desired_sum = input[2]
print correct_change?(nickels, pennies, desired_sum), "\n"
end

• #### Fede

here goes my take!

if (sum % nickels <= pennies && ((nickels *5)+ pennies) >= sum){
return true;
}
else{
return false;

• #### Soner Gönül

Here is mine;

``````    public static bool doStuff(int nickels, int pennies, int sum)
{
if (nickels >= sum / 5)
{
return pennies >= sum - sum / 5 * 5;
}

return false;
}
``````
• #### AMR

I am stuck on this

Quick question - Can this exercise be done only with if statements?

Lang - Python

Appreciate the help

Thank you

• #### Roger

function recipe(sum ,nickels, pennies) {
let nickel = 5 * nickels / 100
let penny = 1 * pennies / 100
let change = nickel + penny
if (penny <= 4 && change % sum === 0) {
return 'true'
} else if (penny > 4) {
return 'false'
} else {
return 'false'
}
};

• #### as;ldkj

All of them work except for Other input which gives me Your Output instead of Other Output.
????

• #### Learneroo

Other input and Other Output are additional cases that aren't displayed on this page. For example, given 5 nickels and 5 pennies, can you reach a sum of 35? Its not possible, but your code returned `true`.

• #### Peter Lacres

I have the same problem. All examples are correct but other input/output isn't. What's wrong with my code? Cant think of a case in which it wouldn't work. It would work with the 5 nickels, 5 pennies and sum 35 example.

• #### Learneroo

@peter, what if you were given 100 nickels, 200 pennies but you needed to get 701 cents? What would your program return then and what should it?

• #### Peter Lacres

Thx, because of the example you have given I was able to find what had to be added to the code. Maybe you should add it to the core I/O instead of other I/O.

• #### David

Cool i actually did not have to modify my code from the previous example, the same one worked :)

• #### saeed

How you must write a good program:
First:Solve the problem yourself
Second:Change your resolution to code exactly
Third:Simplify your code by getting your necessary final conclusion without doing whole operation

• #### Mendel Simon

This one was quite the challenge, but I finally figured it out!
.
.
.
boolean yes=false;
for (int i=0; i<=nickels; i++){
if (5*(nickels-i)<=sum){

• #### shang

``````    if(sum%5 > pennies) {
return false;
}
return nickels*5 + pennies >= sum;
``````

``````public static boolean doStuff(int nickels, int pennies, int sum){
for (int i = 0; i <= nickels; i = i + 1) {
if ( sum - 5 * i <= pennies && sum - 5 * i >= 0) {
return true;
}
}

return false;
}
``````

my code

• #### Prateek

public static boolean doStuff(int nickels, int pennies, int sum){
int a=sum/5;
if(a>nickels){
a=nickels;
}

``````    int b=sum-(a*5);
if(pennies>=b){
return true;
}
return false;
}
``````
• #### Jonathan Solorzano

With my code, Im able to get all correct except the last one with 7, 7, 44..why would it not work?

• #### Paul

Boiler plate code for ruby:

```ruby n = gets.chomp.to_i n.times do input = gets.chomp.split(" ").map(&:to_i) nickels = input[0] pennies = input[1] desired_sum = input[2] print correct_change?(nickels, pennies, desired_sum), "\n" end ```

• #### Кирилл Варивода

I can't even imagine using mod operator "to see if a number ends in 7". Web search didn't helped too.
Also, I do not see a reason to check if number divides by 7.

• #### Кирилл Варивода

I do not see a reason to check if number divides by 7.

I got it.Then I put my code and it all works. It's just a mess of statements.
Now I see Explanation below, it's so easy now using only one if statement!

• #### Davin

This is weird for me, it works until the number 14. How can it be the case?

• #### Learneroo

@Davin, for specific feedback from admins on your code, consider signing up for membership or the bootcamp.

For finding out if the number ends with 7 you should check (number % 10) != 7

• #### Bernard Mitchell

What is the correct phrasing for the print function. I keep getting an error when trying to test my code? Thanks

• #### Bernard Mitchell

I keep getting errors in part of the code that I'm not altering. Can I please get some help on this? Thanks

• #### Learneroo

This usually means you've changed the boilerplate code. In such a case, carefully copy your actual code, click "reset" and try again.

• #### Bernard Mitchell

I keep getting an "cant find symbol error" when I try to print my int.. I'm going to have to cheat on this one. sigh

• #### Bolke

I think I would like to get recognition for possibly having devised the longest, clunkiest and ugliest answer so far:

my code

• #### Bolke

Ha, now I see the pitiful 3 lines of code given as the official answer...That won't cut it.
[insert smiley emoticon here.]

• #### avisuisse

in R

for (i in 1:50) {

if (i == 7) {
next
}
else if (i %% 10 == 7) {
next
}
else print(i)

}

• #### Dheeraj Parmar

#include

using namespace std;

int main()
{

``````for(int i=0;i<=50;i++)
{
if( (i==7) || (i%7==0) || (i%10==7) )
{
continue;

}
else{
cout<<i<<endl;
}
}
``````

}

• #### Matt

Completed successfully, not checked off on the side list, though.

• #### Кирилл Варивода

My code works fine! Admin, thanks you for explanation part after the task, picked up something new!

• #### Davin

Not checked off as well

• #### Learneroo

@Davin, did it get checked off when you went to the next page?

• #### J.g. Dion

'import java.util.*;

public class Main{

``````public static void main(String[] args) {

for (int i=0; i<=100; i = i+1){
``````
• #### Bernard Mitchell

I did mine a different way does it mean my code isn't as efficient or wrote very well?

• #### Learneroo

There are many ways to solve this problem. Run-time efficiency doesn't matter for such small problems, but it's important to try to write clear code. See the featured answers for another possible solution.

• #### z.z

my solution:
for(int i=1;i<=100;i++){

``````        String a=i%5==0?"Buzz":"";
String b=i%3==0?"Fizz":"";
System.out.println(b.length()+a.length()!=0?b+a:i);

}
``````
• #### z.z

for(int i=1;i<=100;i++){

``````        String a=i%5==0?"Buzz":"";
String b=i%3==0?"Fizz":"";
System.out.println(b.length()+a.length()!=0?b+a:i);

}
``````
• #### catypus

My stupid
else if((i%3 ==0) && (i%5==0)){
System.out.println("FizzBuzz");
}

doesn't seem to give FizzBuzz for 15! Why? GRRR

• #### Pedro

@catypus

the order of IF statement is important, if the printIn for 3 has already happened it wont overwrite with 3 & 5 printIn, try making that statement before the 3 and 5 individually.

• #### Kirsten Smith

I'm not sure what to do with the "Other Input" part. Can get everything else to work but don't know what is expected for "Other Input".

• #### Learneroo

@Kirsten, it now shows all 4 cases.

• #### Kirsten Smith

Great, thanks!! That was a super quick fix : )

• #### Victoria Holland

I think there could be a problem with this exercise. It was working fine on the previous page with the hard-coded numbers, but since changing these to the variables n, a and b for this advanced

• #### Learneroo

@Victoria, in this challenge you need to print each word space-separated and only add new lines after each test case. See the "Correct Output" shown above.

• #### Victoria Holland

Thanks, that worked. :)

• #### Dino Šišić

What I did is, make a string and assign values to it inside if statements in a for loop and if a certain condition was met than the string was changed to Fizz or Buzz and printed out, else I printed the number i which is <= n

Hope it helps. :P

• #### saeed

How shoud I define a,b and n?

• #### Learneroo

``````    Scanner in = new Scanner(System.in);

int loops = in.nextInt();

for (int i = 0; i < loops; i++) {

int max = in.nextInt();
``````
• my code
Hey, guys. I got through the last challenge no problem. I also know how to use the Scanner for input, but it doesn't seem to want to run my code based on

• #### Learneroo

You can use the provided boilerplate code to take in input, you don't need your own scanner. Note that each case consists of 3 numbers, `n`, `a` and `b`. Print out `n` items for each case.

• #### Bolke

no featured answer? I know my code sucks, so I'd like to see how it could be done better.

Excellent.

• #### Gary

Confused about declaring n, a, and b. Normally in these challenges these are already declared, but I don't see it in this code. Here is the code I'm using which is which throws a compilation error, even though the same code worked on the previous challenge when n = 100, a = 3, and b = 5:

• #### Learneroo

You can't just compare to `n` without having declared and assigned it. You need to declare the variables yourself (or use actual numbers.)

• #### catypus

I'm expecting t to be an int....
"The input starts with T, the number of cases."

but it compile errors because it says T is a string!

• #### Learneroo

Since this challenge involves standard input, you may want to use the boilerplate code to process the input for you.

• #### Jacknerik

Does ^ not mean "to the power of" in java? I kept trying i2 but that didn't work, so I did i*i and that did.

• #### Learneroo

@jacknerik, ^ does not do "power" in Java. You can see the Java's main built-in math operations here: http://www.learneroo.com/modules/11/nodes/103. Your way was good, though there is also the

• #### Colm Forde

I've entered this code
for (int i = a; i <= b; i ++)
{
return (i * i);
}

when I run the program it tells me I am missing a return statement.

• #### Bernard Mitchell

``````for(int m=a; m<b; m=m+1){
if(m>a&&m<b){
return m*m+b*b+a*a
``````

someone explain why my code is wrong.

• #### Learneroo

Hint: Use a variable to keep track of the total sum and return that at the end.

• #### Bernard Mitchell

@Learneroo I tried creating an int that represents the total. For some reason my int that represents the numbers in the range only picks up the first number in the set. Can you explain what I'm doing wrong?

• #### Learneroo

@Bernard, create a variable `sum` before the loop, and then add the square of each number to `sum`. Then return `sum` after the loop.

• #### Bernard Mitchell

@learneroo when you say create a variable. Do you mean create an int variable? And if so I'm given only the first and last number how can I express the numbers in the range in an int? I was thinking a++.

• #### Learneroo

Yes, create an int variable. Then loop through the numbers from a to b. If you need more help see this code and modify it to add the squares instead of the numbers. See also Math with loops for more practice.

• #### Bernard Mitchell

@leaneroo when i plug in the provided code given in the above comment i get an error. I'm gonna work on it still just wanted to let you know. Thanks

• #### Bernard Mitchell

@learneroo , Finally got it but I don't quite understand still. In my equation does sum remain zero even as the loop goes on. I recall in past nodes that sum changes as the loop goes on. I may be wrong though. Thanks

• #### Learneroo

`sum` is declared outside the loop and set to 0, the loop modifies its value, so after the loop it has the value of whatever it was at the end of the loop. See also scope.

• #### Bryan

Why does this result in "Execution timed out. Please fix your code to execute faster."?

``````static int doStuff(int a, int b){
int sum = 0;
for (int i=a;a<=b;i++) {
int aPow = a*a;
int bPow = b*b;
sum += (aPow*bPow);
}
return sum;
}
``````
• #### Learneroo

Check if the loop will ever terminate. Will there be cases where a will never be less than b, so that the loop goes on forever?

• #### Bryan

Thanks. I just re-read my code after sleeping and can't believe I even wrote that.

• #### avisuisse

sumsquare = function(a, b) {
base = a2
for (i in (a+1):b) {
base = base + i2
}
print(base)
}

• #### omar

//by dart

main() {
var sum = SumoftheSquares(1, 3);
print(sum);
}

SumoftheSquares(a, b) {
int thesum = 0;
for (int i = a; i <= b; i++) {
thesum += i * i;
}
return thesum;
}

• #### 許友誠

import java.util.Scanner;

public class Main {

``````static int doStuff(int a, int b)
{
int count=b;
int  ans=1;

for(int i=0;i<b;i++)
``````

my code

• #### Bolke

That was tricky. Took me! my code

• #### zkvarz

Quite simple, one problem was to stop the toop, eventually I've managed it.

• #### David

For me it wasn't about stopping the loop but actually how to get the number print the first time(initial input) and the last time (1) without having the loop interfering.

• #### Mikas

Whats wrong with my code? It keeps giving me the "Runtime error"

``````public static void doStuff(int num){
System.out.print(num + " ");
while(num > 1){
``````
• #### Melany

@Mikas Your else says "num = num * 3 - 1" it should be +1.

• #### Jig

I dont understand why would 3-1 cause runtime error?

• #### Learneroo

@Jig, you can get stuck in a loop, eg 5, 14, 7, 20, 10, 5 ...

• #### Jig

How did you know that it would get stuck in a loop. Thanks for the insight. Love what you guys are doing.

• #### Bernard Mitchell

@Learneroo should I create two loops?

• #### Learneroo

@Bernard, that's not necessary. You can create one `while` loop, with a condition inside it that determines what number to go to next.

• #### Ravi

for input=5 , the output should be 16 8 4 2 1

• #### Learneroo

Sorry, due to a change yesterday it was mistakenly showing the number 5 for the count, it's been fixed.

• #### zkvarz

Three examples above shows correct, but "other output" is wrong. Maybe I misunderstood the task, maybe it's better to show more examples in I/O.

• #### Learneroo

@zkvarz, you can now view more cases.

• #### zkvarz

Thank you for cases, admin! I think this way:
In this case we can't divide 5 evenly so we divide 10 until we get smallest even number 2, therefore 5*2 = 10.

• #### zkvarz

so we divide 10 by 5. I still can't get it, why not 2

• #### zkvarz

Admin, I thought I get this task but still, "other output" is wrong. Something I do the wrong way.

• #### David

On the Explanation:

"Explanation: You could use a while loop, or a compact for loop:

int i;
for(i=1; a*i % b != 0; i = i +1 ){

• #### Learneroo

@David, `i` will keep increasing until `a*i` is a product of `b`. So it will stop when i=5 and a=3 and return that product.

• #### 許友誠

import java.util.Scanner;

public class Main {

``````static int doStuff(int a, int b)
{

int max=1;
for(int i=2;i<=a;i++)
{
if(a%i==0 && b%i==0)
``````
• #### kevintaw

A little difficult

• #### Jig

This worked for me but I don't understand it, anyone please explain

``````    int multiple =0;
for(int i=1; i<=100; i++){
multiple=a*i;

if (multiple%b ==0 && multiple%a==0){
return multiple;

}
}
return multiple;
``````
• #### Bernard Mitchell

``````int c=0;
while(c%b!=0){
c=c+a;
}
return c;
``````

I don't understand why my code isn't working.

• #### Learneroo

If `c` is 0 , what happens when you reach the while condition? (You should always test out smaller parts of your code to know what's going on.)

• #### thales

Is this a smart solution. I mean it does makes a different if a<b or b<a right?

my code

• #### arya

int LCM = 1;
while (!(((LCM % a) == 0) && ((LCM % b) == 0))){
LCM++;
}
return LCM;

• #### avisuisse

in R
leastcm = function(a, b) {

status = F

while(status == F) {

``````for (i in a:(a*b)) {

if (i %% a == 0 & i %% b == 0) {
status = T
print(i)
break
}
}
``````

}
}

• #### avisuisse

leastcm = function(a, b) {

status = F

while(status == F) {

``````for (i in a:(a*b)) {

if (i %% a == 0 & i %% b == 0) {
status = T
print(i)
break
}
}
``````

}
}