As the title suggests, I have code for a Fibonacci series and my goal is to replace multiples of numbers (3, 5, 7 and combinations of them) in the series with a word. I was suggested to use a flag in my if loop to check for the printed phrase, and if the phrase is printed, to skip that number. Essentially, what I want the output to look like is:
1 1 2 skip 8 13 skip 34 55
(this is replacing multiple of three only, for now).
Instead, what I am getting is:
1 1 2 3 skip5 8 13 21 skip34 55
Here is my code as of now:
int febCount = 50;
long[] feb = new long[febCount];
feb[0] = 1;
feb[1] = 1;
for (int i = 2; i < febCount; i++) {
feb[i] = feb[i - 1] + feb[i - 2];
}
for (int i = 0; i < febCount; i++) {
System.out.print(feb[i] + ((i % 10 == 9) ? "\n" : " "));
if (feb[i] % 3 == 0)
System.out.print("skip");
}
Any and all help is appreciated!
Let's walk through the code you have provided and attempt to understand why it's not working.
//The first thing we do is setup the loop to iterate through the fib numbers.
//This looks good.
for (int i = 0; i < febCount; i++) {
//Here we print out the fibonacci number we are on, unconditionally.
//This means that every fibonacci number will be printed no matter what number it is
//we don't want that.
System.out.print(feb[i] + ((i % 10 == 9) ? "\n" : " "));
//After we print the number, we check to see if it is a multiple of three.
//maybe we should be waiting to print until then?
if (feb[i] % 3 == 0)
System.out.print("skip");
}
Now that we have walked through the code, we can propose a new solution.
Let's try updating the loop so that it wait's to print the fibonacci number until AFTER we've checked to see if it meets our conditions.
for (int i = 0; i < febCount; i++) {
if (feb[i] % 3 == 0 || feb[i] % 5 == 0 || feb[i] % 7 == 0) { //check if multiple of 3 5 or 7
System.out.println(" Skip ");
} else { //if it's not a multiple, then print the number
System.out.println(" " + feb[i]);
}
}
Related
i'm just started to learn java yesterday. But, now i met difficulty to show the arithmetic progression like the display below:
1 2 2 2 3 3 3 3 3 4 4 4 4 4 4 4
From that example, i know that every odd numbers, the numbers increment. I've tried to make it, but the display just keep showing like this:
2 4 4 4 6 6 6 6 6 8 8 8 8 8 8 8 10 10 10 10 10 10 10 10 10
Here's my code:
for (int i = 0; i <= 10; i++) {
if (i % 2 == 0) {
for(int j = 1; j<i; j++){
System.out.print(i + " ");
}
}
}
And then, i want to take the last value of it. For example, if i have row = 3, it must be value = 2.
because :
row = 1 2 3 4 5 6 7 8 9 10
value = 1 2 2 2 3 3 3 3 3 4
Would you tell me, what line is exactly must be fix? Thank you
It's not about a line that is wrong, it's your approach that's a bit off. You could fix it in multiple ways. Easiest (but not most efficient) way is this:
for (int i = 0; i <= 10; i++) {
if (i % 2 == 0) {
for(int j = 1; j<i; j++){
System.out.print((i/2) + " ");
}
}
}
As you can see, only the output was changed and now it works. However, iterating over 11 numbers (0-10) when you only really care about 4-5 is not necessarily the best way to go here.
It also doesn't make your code easy to understand.
Here's an alternative.
int amount = 1;
for (int i = 1; i <= 5; i++) {
for (int j = 0; j < amount; j++) {
System.out.print(i + " ");
}
amount = amount + 2;
}
Here you can see that the outer for has been changed to only take the numbers we actually care about, which means we can remove the if completely.
We just have to somehow decide how many times we want to execute the print call, which is done with the amount variable.
Try this.
for (int i = 1, r = 1; i <= 4; ++i, r += 2)
System.out.print((i + " ").repeat(r));
You can calculate value from row with this method.
static int value(int row) {
return (int)Math.ceil(Math.sqrt(row));
}
So you can also do like this.
for (int row = 1; row <= 16; ++row)
System.out.print(value(row) + " ");
result:
1 2 2 2 3 3 3 3 3 4 4 4 4 4 4 4
Hey it's a representation of a sequence that grows by 2 every step.
i.e the first element is 1 which shows up one time.
the second element is 3 which shows up 3 times (2 2 2)
and so on and on..
so the code you need is:
int a = 1;
for(int i=1; i<=10;i++){
int j=1;
while(j<=a){
System.out.print(i);
j++;
}
a+=2;
}
printing the value in a wanted row:
Scanner in = new Scanner(System.in);
int rowU = in.nextInt(); // User inputs row
int row = 1; // a variable to keep track of the rows
int repeats = 1; // the number of times a value shoud appear
for(int value=1;value<=10;value++){
int j=1;
while(j<=repeats){
if(row==rowU) // if we got to the wanted row
System.out.println(value); // print the wanted value
j++;
row++;
}
repeats+=2;
}
There is a better, more efficient way to get the value of a wanted row:
int wanted_value = Math.ceil(Math.sqrt(wanted_row));
Thanks to #saka for bringing this one up!
Hope I helped :)
i % 2 == 0 means that the following code is only going to be executed, if i is even.
You could try removing the if, and change the second for to something like
int j = 0; j < 2 * i - 1; j++.
This code snippet will do the work
int n=4;
int printTimes=1;
for(int i=1;i<=n;i++)
{
for(int j=0;j<printTimes;j++)
System.out.print(i+" ");
printTimes+=2;
}
System.out.println();
Here is the example code.
int start = 1;
int end = 5;
int time = 1;
for (int i = start,j = time; i < end; i++,j+=2) {
for (int k = 0; k < j; k++) {
System.out.print(i+" ");
}
}
You must deliver exactly N kilograms of sugar to a candy store. The sugar made in the sugar factory is contained in a bag. The bag has 3 kg bag and 5 kg bag.
I try to carry as little bags as possible. For example, when you need to deliver 18 kilograms of sugar, you can take 6 bags of 3 kilograms, but if you deliver 3 kilograms and 3 kilograms, you can deliver a smaller number of bags.
Write a program to find out the number of bags you should take when you have to deliver exactly N kilograms of sugar.
(3<=N<=5000 AND If you can not make exactly N kilograms, print -1.)
In case of only 4 or 7 , it is not divided so I made it to print -1.
And to get the minimum bag, I used the code below.
But when I run this, the case if it is not divided by 5 or 3, the bottom sentence should be printed out but it is not working.
I want to know how does it works. Thank you.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int N = input.nextInt();
if (N % 5 == 0) {
System.out.println(N / 5);
} else if (N == 4 || N == 7) {
System.out.println(-1);
} else
for (int i = 1; (N - 3 * i) % 5 != 0; i++) {
if ((N - 3 * i) % 5 == 0)
System.out.println(i + (N - 3 * i) / 5);
break;
}
}
}
Looks there is a logic issue with your solution. Try the following :
boolean isPossible = true;
if (N % 5 == 0) {
System.out.println("You need : " + (N / 5) + " bags");
} else {
int diff = 0;
for (int i = N; i > 0 && N >= 0; i--) {
if (N % 5 != 0) {
diff = N % 5;
N = N - diff;
} else {
if (diff % 3 == 0) {
System.out.println("You need : " + (N / 5 + diff / 3) + " bags");
isPossible = true;
break;
} else {
N = N - 5;
diff = diff + 5;
}
}
}
}
if (N <= 0 || !isPossible)
System.out.println(-1);
Logic is explained below :
Basically here we find the modulus of N with 5 and check if the
remainder (in the example diff) is a multiple of 3.
If the remainder (diff) is not a multiple of 3 then we reduce N by
5 and increase diff by 5. This continues until we have found a match (isPossible) or else if not found -1 is printed out.
So as far as I understand, you're trying to use the smallest amount of 3kg bags in the last for loop and you want to break out as soon as the remainder is divisible by 5kgs.
(int i = 1; (N - 3 * i) % 5 != 0; i++)
Could you not have the middle part as i < 5?
(int i = 1; i < 5; i++)
Also, you could get rid of the if condition
if (N % 5 == 0) {
part by starting i at 0, so you account for the case N is divisible by 5:
(int i = 0; i < 5; i++)
Scanner input = new Scanner(System.in);
int N = input.nextInt();
int sum = 0;
boolean isFound = false;
for (int i = 0; i < N / 2; i++) {
for (int j = 0; j < N / 2; j++) {
if ((5 * i) + (3 * j) == N) {
sum = i + j;
isFound = true;
}
}
}
if (isFound ) {
System.out.println("You require " + sum + " bags");
} else {
System.out.println(-1);
}
Explanation:
The above code aims to find the possible combinations of the sum of the factors of 3 and 5 that give the number, i.e N:
For example:
N = 32
For each iteration, the following condition is checked.
if((5 * i) + (3 * j) == N)
The check continues until the smallest numbers that satisfy the condition are found.
5*0 + 3*0 = 0 which is not equal to 32
5*0 + 3*1 = 3 which is not equal to 32
5*0 + 3*2 = 6 which is not equal to 32
.
.
5*1 + 3*0 = 5 which is not equal to 32
5*1 + 3*1 = 8 which is not equal to 32
5*1 + 3*2 = 11 which is not equal to 32
5*1 + 3*4 = 17 which is not equal to 32
.
.
5*4 + 3*0 = 20 which is not equal to 32
5*4 + 3*1 = 23 which is not equal to 32
5*4 + 3*2 = 26 which is not equal to 32
5*4 + 3*3 = 29 which is not equal to 32
5*4 + 3*4 = 32
In this case, i=4 and j=4, i.e sum of bags required (i+j) = 8
isFound is set to true to indicate that the combination is found.
If no combination is found, isFound remains to be false, and -1 is printed.
I have this HW assignment that I'm stuck in:
I need to write the sequence from 1 until N given seed.
for example:
if user inputs 4 v then I need to write every line from the first sequence until the 4th and then write down how many have reached 1 in the end and count the number of numbers.
example:
1 4 2 1 (4)
2 1 (2)
3 10 5 16 8 4 2 1 (8)
4 2 1 (3)
s.o.p :The first 4 hailstone sequences reached 1.
if user inputs 7 c then I only need to write the sentence The first 4 hailstone sequences reached 1.
so far I've written the code for the v part,
the part that works:
public class Collatz {
public static void main(String[] args){
int n = Integer.parseInt(args[0]);
String str = String.valueOf(args[1]);
int counter = 1;
if (str.equals("v")) {
while (n != 1)
{
System.out.print(n + " ");
// If n is odd
if ((n & 1) == 1) {
n = 3 * n + 1;
}
// If even
else{
n = n / 2;
}
counter++;
}
// Print 1 at the end
System.out.print(n + " (" + counter + ")");
}
}
}
I have tried putting a for loop to print from 1 to n in order to print like my example but it doesn't, my attempt:
` for (int i = 1; i < n; i = i+1){
while (i!= 1) {
System.out.print(i + " ");
// If n is odd
if ((i & 1) == 1)
i = 3 * i + 1;
// If even
else
i = i / 2;
}
// Print 1 at the end
System.out.print(i); `
no go. please help me debug this.
Solved it:
add: before the while
for (i = 1; i <= n; i = i+1){
hail = i; // we need to make sure i isn't run over
int counter = 1;
How to print the following output with only one for-loop in java?
1 2 3 4 5 6 7 8 9 1 0 9 8 7 6 5 4 3 2 1
Code snippet:
class Series{
public static void main(String args[]){
for(int i=1; i<=10; i++){
System.out.println(i);
}
System.out.println(i);
for(int j=9; j>=0; j--){
System.out.println(j);
}
}
My program's in the following manner. Can anyone correct it?
public static void main(String...strings ){
int dir = 1;
for(int i=1; i>0; i+=dir){
if(i == 10)
dir = -1;
System.out.print(i+" ");
}
}
Output:
1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1
The series in the question is wrong.
It should be: 1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1
The code, in one loop, is as follows:
int ctr = 1;
for(int i = 1; i > 0; i += ctr)
{
if(i == 10)
{
ctr = -1;
}
System.out.print(i + " ");
}
Every sequence follows a pattern, Let's try finding one in this.
To work with this code, analyze What loop would print with the variable that you increment and What you want in the output?
In your problem, assuming that the number you are entering is entered by user i.e. n, you want 2*n - 1 numbers in your sequence. Hence we now have the limits of our loop
For n=5, Under no Conditions the loop would simply print a sequence like this
1 2 3 4 5 6 7 8 9 provided you are starting your loop from 1.
The sequence you want is 1 2 3 4 5 4 3 2 1.
Now looking at both the sequences you can see that the sequence is same till the mid point that is till the value of n is reached. Now if you observe the pattern further if you subtract 2 from 6 you get 4 that is the number you want in your sequence. Similarly when you subtract 4 from 7 you get 3 which is the next number in the sequence you required.
Hence the pattern this sequence follows is that after the loop reaches the value provided by the user you need to subtract (2 * k) from the next number where k starts from 1 and increases with every iteration
Now you know how to achieve the pattern which would be easy to achieve using conditional statements.
PS: let's assume an added constraint of using no conditional statements then we have to write an arithmetic expression to solve our problem.
Following the pattern again the expression must display i where i is the variable incremented in the loop
so our code looks like
for (i = 1; i<=2*n - 1;i++)
{
System.out.print(i);
}
Now to get the pattern we need to subtract multiples of 2 after the user provided integer n is reached. But whatever we subtract should also not affect out first n integers.
Since we know we have to subtract multiples of 2 we know the expression we have to subtract would look like 2 * (____). As we want a sequence of multiples we can obtain that using %. As soon as the number goes over n the % operator on i would give us back sequence from 0 to n-1 hence generating multiples of 2.
Now our expression comes to 2 * (i % n). But the problem is that it would also subtract from the first 4 integers which we don't want so we have to make changes such that this expression will work only after loop reaches the value provided by the user.
As we know the division / operator provides us with the quotient. Hence it would yield us 0 till we reach the value of user defined number and 1 for the rest of the sequence as we run our loop till 2*n -1. Hence multiplying this expression to our previous expression yields 2*(i%n)*(i/n)
And there we have it our final code to generate the sequence would be
for (int i = 1;i<2*r;i++)
{
System.out.print(i - 2 * (i%r)*(i/r));
}
Observe the above code for the first n-1 integers i/r would make subtracted expression 0 and for i = n, i % r would make the expression 0. For the rest of the sequence i / r would generate value 1 and hence we will get multiples of 2 from 2 *( i % r) to provide us with the sequence
try this
int j = 10;
for (int i = 1; i <= 10; i++) {
if(i<10)
System.out.print(" " +i);
if(i==10){
i--;
System.out.print(" " +j);
if(j==1){
i++;
}
j--;
}
}
OutPut
1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1
Something like this?
for(int i=0;i<20;i++) {
if((i/10)%2 == 0)
System.out.print(i%10 + " ");
else
System.out.print((10-(i%10)) + " ");
}
Try this code, You just need a if condition in for loop.
int i = 1;
for(int j=1; j<=20; j++)
{
if(j<11)
System.out.print(j+" ");
else
{
System.out.print((j - i == 10 ?" ": (j-i + " ")));
i = i+2;
}
}
public class forLoopTest {
public static void main(String[] args) {
for (int i = 1; i < 10; i++) {
System.out.print(i + " ");
}
for (int j = 10; j >= 1; j--) {
System.out.print(j + " ");
}
}
}
So, I want to find what numbers between 1 and 100 are divisible by 3 and 7. I got it to work, except for one of the numbers. For some reason, 3 % 3 is giving me 3 as a remainder, but 6 % 3 is giving me 0. This is my code:
public class factors
{
public static void main(System args[])
{
//Variables
int integer, remainder;
//Displays header
System.out.print("Integers less than 100 that are \nevenly divisible by 3 or 7");
//Loops through each integer
for (integer = 1; integer <= 100; integer++)
{
remainder = integer % 3; //determines if 3 is a factor
if (remainder == 0) //displays integer
{
System.out.println(integer + " is divisible by 3");
}
remainder = integer % 7; //determines if 7 is a factor
if (remainder == 0) //displays integer
{
System.out.println(integer + " is divisible by 7");
}
}
}
}Does anyone know why this isn't working for the number 3?
You code is actually doing
remainder = 3 % 7; // equals 3.
The best way to determine why your code is not doing what you think is to step through your code using a debugger.
All the multiples of 3 & 7 will be multiples of 21, i.e. 21, 42, 63, 84.
Your 3 is getting tacked onto the end of the line of text above. You'll be seeing
Integers less than 100 that are
evenly divisible by 3 or 73
because you wrote print instead of println for this line of text. The % operator is working just fine, and 3 % 3 is indeed 0, not 3.
You are not outputting a remainder - you are displaying integer. So for 3 it should print 3.
Make you print statements more definite:
System.out.println(integer + " is divisible by 3"); // for the first `if`
and
System.out.println(integer + " is divisible by 7"); // for the second `if`
This should clear your confusion.
Your logic prints number divisible by 3 or 7.
Firstly, your code can be shortened to:
//and
for (int i = 1; i <= 100; i++){
if(i % 3 == 0 && i % 7 == 0) {
System.out.println(i);
}
}
//or
for (int i = 1; i <= 100; i++){
if(i % 3 == 0 || i % 7 == 0) {
System.out.println(i);
}
}
Also I note you're not declaring a type for your integer, remainder variables. I didn't attempt to recreate with those issues; start by solving that.