int cnt = 0, sum = 0;
for(int i = 1; ((i <= 1000) && (i%3 == 0) && (i%5 == 0)); i++){
if(cnt >= 5)
break;
System.out.println(i);
sum += i;
cnt++;
}
System.out.println(sum);
I want to get the first 5 numbers that are divisible by 3 as well as 5 between the range of [1, 1000]. This code does not shows any error but it returns 'sum' and 'cnt' both to it's default values (i.e. 0) and seems to me that it's not entering the for loop.
P.S. I am not advance level programmer. I'm trying this stuff just for exploration, so if any one could explain the actual reason behind this.
It sounds like you do not understand how a for loop works. #Silvio Mayolo and #experiment unit 1998X commented some very helpful links. I would encourage you to read through those and get comfortable with them.
In your example, your for loop has a very complex header.
for(int i = 1; ((i <= 1000) && (i%3 == 0) && (i%5 == 0)); i++){
Let's break this apart into sections.
for -- this is the keyword that starts the for loop
int i = 1; -- now you have created a variable in your loop. It is an int called i, and it has a starting value of 1.
(the termination expression) -- If the termination expression returns false, then loop stops looping. Let's see how you used it
i <= 1000 -- now you have added a rule --> in order for the for loop to perform a loop, the number i must be less than or equal to 1000. Ok, that is simple enough, you are now going to have at least 1000 valid values for i thus far.
i%3 == 0 -- now you have added another rule --> in order for the loop to perform a loop, the number i must have no remainder when divided by 3. Unfortunately, that is a problem because your starting value for i is 1, as mentioned earlier, and 1/3 DOES have a remainder. Therefore, the loop stops before it even starts.
This is your problem. If you want to check and see if i%3 == 0, you should not put that check inside of your termination expression. It should go inside of the enclosing block within the for loop. And the same applies for i%5 == 0.
Here is a runnable example to help you understand.
public class SOQ_20220516
{
public static void main(String[] args)
{
int cnt = 0;
int sum = 0;
for(int i = 1; i <= 1000; i++)
{
if(cnt >= 5)
{
break;
}
if ((i%3 == 0) && (i%5 == 0))
{
System.out.println(i);
sum += i;
cnt++;
}
}
System.out.println(sum);
System.out.println(cnt);
}
}
public class SOQ_20220516
{
public static void main(String[] args)
{
int cnt = 0;
int sum = 0;
for(int i = 1; i <= 1000; i++)
{
if(cnt >= 5)
{
break;
}
if ((i%3 == 0) && (i%5 == 0))
{
System.out.println(i);
sum += i;
cnt++;
}
}
System.out.println(sum);
System.out.println(cnt);
}
}
Blockquote
Related
Trying to create a method to return the first number below "n" which can be entirely divided by both the first and second divisor. Currently my program is returning the default value of "answer" being 0, I want the value which is calculated within the loop to be translated outside the loop to be returned. Yes I am a beginner :(
static int highestNumberBelowNDivisibleByTwoNumbers(int firstDivisor, int secondDivisor, int n) {
int multipliedDivisors = firstDivisor * secondDivisor;
int answer = 0;
int remainder = 0;
for (int i = n; i <= 1; i--) {
remainder = multipliedDivisors / i;
if (remainder == 0){
answer = i;
break;
}
}
return answer;
}
Based on your description of:
Trying to create a method to return the first number below "n" which
can be entirely divided by both the first and second divisor.
Try something more like below with the % operator (remainder/modulo):
static int highestNumberBelowNDivisibleByTwoNumbers(int firstDivisor, int secondDivisor, int n) {
while (n>0) {
if ((n % firstDivisor == 0) && (n % secondDivisor == 0)) {
return n;
}
n--;
}
return -1; // no answer found
}
Your code
for (int i = n; i <= 1; i--) {
remainder = multipliedDivisors / i;
if (remainder == 0){
answer = i;
break;
}
Decreases the counter from n down to 1. HOWEVER, your answer is not updated UNLESS remainder equals to zero. If that condition is never met, the default value of n will be returned (which is zero).
The problem? remainder = multipliedDivisors / i when will remainder be zero?
Because of this assignment, int multipliedDivisors = firstDivisor * secondDivisor;, only if one of the "divisor" variables is zero.
Redo your logic.
i want to create java program for a number when divided by 2, 3, 4, 5, 6 leaves a remainder of 1 but it is divided by 7 completely.
I tried this logic
for (int a=1;a<=500;a++){
if (a%2==1 && a%3==1 && a%4==1 && a%5==1 && a%6==1 && a%7==0)
and it works fine but I want it by this logic
for (int a=1;a<=500;a++){
for(int b=2;b<=6; b++){
if (a%b==1 && a%7==0){
System.out.println(a);
help me if it is possible to create in this way?Thank you
You could count how many of the iterations pass your test, like this:
for (int a=1; a<=500; a++) {
int flag=0;
for (int b=2; b<=6; b++) {
if (a%b == 1) {
flag += 1;
} else {
break;
}
}
if (flag == 5) {
if (a%7 == 0) {
System.out.println("Value "+a);
}
}
}
If any of the tests fail, flag will be less than 5 at the end of the loop. If you change the number of tests, you will need to remember to update that magic number.
you could name the outer loop and check and continue it in the inner loop like this:
public static void main(String[]args){
// That´s your mainloop
mainLoop: for (int a=1; a<=500; a++){
for(int b=2; b<7;++b) {
// If anything doesn´t leave a remainder of 1 youll continue with the mainloop here
if(a%b != 1) {
continue mainLoop;
}
}
// 2-6 had a remainder of 1, so just check if the number is dividible by 7 now, if so print it.
if(a%7 ==0) {
System.out.println(a);
}
}
}
It can make things easier if you split your code into functions. Start with the outer (a) loop:
public static void main(String[] args)
{
for (int a = 1; a <= 5000; ++a)
if (test(a))
System.out.println(a);
}
We've deferred the actual logic to the test() function, and assumed we'll define that later.
Now write the test. As soon as any of the sub-tests fail, we can return false immediately. If all tests pass and we reach the end, then we must return true:
static boolean test(int x)
{
// i is the candidate factor
for (int i = 2; i <= 7; ++i) {
int expected = i==7 ? 0 : 1;
if (x%i != expected)
return false;
}
return true;
}
We can simplify further through use of a magic number to encode the different values of expected:
static boolean test(int x)
{
for (int i = 2; i <= 7; ++i)
if (x%i != 301%i)
return false;
return true;
}
You can iterate over all the b values, and set a flag if any of them fail the test. If the flag is unset at the end of the loop, you know they all passed:
for (int a=1; a<=500; a++) {
int flag = 0;
for (int b=2; b<=6; b++) {
if (a%b!=1 || a%7!=0) {
// doesn't satisfy the condition, so flag it
flag = 1;
break; // exit the inner loop
}
}
if (flag == 0)
// If we got here without setting flag, it means that all of the
// 'b' values passed the test.
System.out.println(a);
}
It now can find all the prime numbers in the input range, but it can't find number 2, the smallest prime number.
for(int number=2;number<range;number++){
for(int testDivide=2;testDivide<Math.sqrt(number);testDivide++){
if(number%testDivide!=0) {
System.out.println(number);
}
break;
}
For range 10 it prints:
5
7
9
but no 2.
The reason your code is not producing correct results (missing 2 and 3; including 9) is that your primality test logic is backwards. A number is prime if the inner loop completes without finding any even divisors; instead you are printing the number if you find any non-divisor.
Try this instead:
for( int number = 2; number < range; number++) {
boolean divisible = false;
int limit = (int) Math.sqrt(number);
for (int testDivide = 2; !divisible && testDivide <= limit; testDivide++) {
divisible = number % testDivide == 0;
}
if (!divisible) {
System.out.println(number);
}
}
Note that a much more efficient way to generate all primes in a range is the Sieve of Eratosthenes.
check the code here:
package core;
public class Test2 {
public static void main(String[] args) {
int cnt = 0;
for (int i = 2;; i++) {
if (Priem(i)) {
cnt++;
System.out.println(i);
if (cnt == 200)
break;
}
}
}
public static boolean Priem(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
Note that one of the best ways to generate a list of prime numbers is the "Sieve of Erwhatshisface":
Create a list of consecutive integers starting with 2, up to the max number you'd like to search. Take the first non-zero number in the list (2) and repeatedly step 2 from that location, zeroing out every 2nd list element.
Next take the second non-zero number (3) and repeatedly step 3 from that location, zeroing. Continue with each non-zero value in the list, until you've processed all of them (or at least halfway through, at which point you'll be stepping beyond the end of the list).
The non-zero numbers remaining are all primes.
Reposting code here as not fit in comments:
public static void main(String[] args) {
int cnt = 0;
for (int i = 2;; i++) {
if(i==2){
System.out.println(i);
continue;
}
if (Priem(i)) {
cnt++;
System.out.println(i);
if (cnt == 200)
break;
}
}
}
public static boolean Priem(int n) {
for (int i = 2; i <Math.sqrt(n)+1; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
I think you have your for loop a little mixed up.
for(int testDivide=2;testDivide<Math.sqrt(number);testDivide++){
}
Not sure why you are stopping when testDivide is equal to sqrt(number), you should stop when testDivide is greater than.
Also inside your inner for loop isn't correct either:
if(number%testDivide!=0) {
System.out.println(number);
}
break;
Basically all this will do is check to see of the number is divisible by 2 and then break. You only need to break when you find a number which cleanly divides (number%testDivide==0). Maybe keep a boolean which you set to true when you break and only print after the inner for loop finishes if that boolean is false.
Something along the lines:
for (int number=2; number<range; number++){
boolean found = false;
int limit = (int)Math.sqrt(number);
for (int testDivide=2; testDivide<=limit; testDivide++){
if(number%testDivide==0) {
found = true;
break;
}
}
if (!found) System.out.println(number);
}
In your code when number is 2, sqrt(2) is 1.41 and control doesn't go into the loop. I didn't get the logic behind iterating upto sqrt(number). Try this code
public class Test {
public static void main(String[] args) {
int range = 500; //I assume
for (int i = 2; i< range; i++) {
if (isPrime(i)) {
System.out.println(i);
}
}
}
public static boolean isPrime(int number) {
for (int i = 2; i <= number/2; i++) {
if (number % i == 0) {
return false;
}
if(i % 2 == 1) {
i++; //If not divided by 2 then
// need not to check for any even number
// Essentially incrementing i twice hereafter
}
}
return true;
}
}
I need to write a program to generate some random numbers without having two numbers fall in a certain range. Unfortunately, I need to do it at school and the only language I can use on the computers is Java (I would otherwise do it in C++). I know very little Java, and my program is giving me a stack overflow after generating 20 or so numbers. Could someone please explain why? The program is somewhat ugly, but I really need it ready in a hurry.
import java.io.*;
import java.util.*;
public class RandomNumbers {
public static int GenerateNumber(int previousNumber, int[] numberUsed) {
Random random = new Random();
int number = random.nextInt(39);
if (previousNumber >= 1 && previousNumber <= 9) {
while (number >= 1 && number <= 9)
number = random.nextInt(39) + 1;
} else if (previousNumber >= 10 && previousNumber <= 17) {
while (number >= 10 && previousNumber <= 17)
number = random.nextInt(39) + 1;
} else if (previousNumber >= 18 && previousNumber <= 32) {
while (number >= 18 && previousNumber <= 32)
number = random.nextInt(39) + 1;
} else if (previousNumber >= 33 && previousNumber <= 41) {
while (number >= 32 && number <= 41)
number = random.nextInt(39) + 1;
}
return number;
}
public static void main(String[] args) {
int[] numberUsed;
numberUsed = new int[40];
for (int i = 0; i < 40; ++i) {
numberUsed[i] = 0;
}
int previousNumber = 0;
for (int y = 0; y < 40; ++y) {
int number = 1;
while (numberUsed[ number = GenerateNumber
(previousNumber, numberUsed) ] != 0);
numberUsed[number] = 1;
previousNumber = number;
System.out.println(y);
}
}
}
EDIT: Okay, so now, for some reason, the for loop (the one with y as a counter) is not running 40 times when I include the while loop. Can someone explain why this is happening?
Your function will eventually have a problem to ever return to the main.
You will face a recursion problem in
if (numberUsed[number] != 0) {
return GenerateNumber(previousNumber, numberUsed);
}
As the array get's filled up with 1s, this will continue to execute the function call instead of actually successfully returning. It will execute the function recursively, eventually causing the stack overflow.
When you call the function again, your parameters (previousNumber and numberUsed) are identical to the last execution, nothing changes. You keep running into the same problem since the chance of hitting a non-zero is so high, so the recursion just stacks up forever and eventually crashes.
You should get rid of the if statement in the function and just return the number back to main and do your checks there.
You start with a zero'd out array, that you gradually fill with 1s and never reset them to 0. When most of the elements of the array are non-zeros, you have a very high chance of calling GenerateNumber recursively in a very deep nesting, which is what you experience.
Also, you never change previousNumber in GenerateNumber, so you will always go down the same path, regardless of the random number generated.
After staring at this for a while, I think I figured out a working solution. It's still really ugly, but you seem to be OK with that.
public static int GenerateNumber(int previousNumber,
int[] numberUsed) {
Random random = new Random();
int number = random.nextInt(39);
while (numberUsed[number] != 0) {
number = random.nextInt(39);
if (previousNumber >= 1 && previousNumber <= 9) {
while (number >= 1 && number <= 9)
number = random.nextInt(39) + 1;
} else if (previousNumber >= 10 && previousNumber <= 17) {
while (number >= 10 && previousNumber <= 17)
number = random.nextInt(39) + 1;
} else if (previousNumber >= 18 && previousNumber <= 32) {
while (number >= 18 && previousNumber <= 32)
number = random.nextInt(39) + 1;
} else if (previousNumber >= 33 && previousNumber <= 41) {
while (number >= 32 && number <= 41)
number = random.nextInt(39) + 1;
}
}
return number;
}
On a side note the run-time will also be atrocious as you get towards the end of the list, but it shouldn't stack overflow. Also it might infinite loop now that I think about it, you probably need to redesign this entirely.
StackOverFlow happens because of overlapping of methods/constructors, etc. I here,
if (numberUsed[number] != 0) {
return GenerateNumber(previousNumber, numberUsed);
}
this code is inside the GenerateNumber method and it is keep on calling the same method. That's the reason. If you want to check it, remove that part and try, it will compile fine. To get rid of this, eliminate the above process.
You can do it by using a loop, while loop, and putting all of your if else statements inside that
This code detects a cul-de-sac and keeps restarting until it reaches the end (typically it does only one or two retries). It also directly chooses a random number from the collected sequence of allowed choices, so no stochastic runtime for any single try.
import java.util.Arrays;
import java.util.BitSet;
import java.util.Random;
public class RandomNumberGenerator {
static final Random random = new Random();
static final BitSet usedNumbers = new BitSet(40);
static final int[] ticks = {0, 1, 10, 18, 33, 41};
static int previousNumber;
public static int generateNumber() {
for (int i = 1; i < ticks.length; i++)
if (previousNumber < ticks[i])
return generateOutsideRange(ticks[i-1], ticks[i]);
return generateOutsideRange(0, 0);
}
static int generateOutsideRange(int low, int high) {
final int[] numsToChoose = new int[40];
int choiceLimit = 0;
for (int i = (low > 1? 1 : high); i < 41; i = (++i == low? high : i))
if (!usedNumbers.get(i)) numsToChoose[choiceLimit++] = i;
if (choiceLimit == 0) throw new CulDeSacException();
final int r = numsToChoose[random.nextInt(choiceLimit)];
usedNumbers.set(r);
previousNumber = r;
return r;
}
public static void main(String[] args) {
while (true) try {
usedNumbers.clear();
previousNumber = -1;
final int[] rands = new int[40];
for (int i = 0; i < rands.length; i++) rands[i] = generateNumber();
System.out.println(Arrays.toString(rands));
break;
} catch (CulDeSacException e) { System.out.println("Retry"); }
}
}
class CulDeSacException extends RuntimeException {}
Is this the spected behavior? "Shuffling the Array"
ArrayList<Integer> numbers = new ArrayList<Integer>();
int[] scrambled = new int[40];
Random rnd = new Random();
for(int i=0;i<scrambled.length;i++){
numbers.add(i+1);
}
int idx=0;
while(!numbers.isEmpty()){
int pos = rnd.nextInt(numbers.size());
scrambled[idx] = numbers.get(pos);
numbers.remove(pos);
idx++;
}
for(int i=0;i<scrambled.length;i++){
System.out.println(scrambled[i]);
}
in the inner for loop I have 0<p1,p2,p3<3 and they are integer. I want this for loop to assign value from 0 till 3 to each parameter in demoMethod.i.e., once the for loop executes it will send parameter like (1,2,3) to demomethod and for the second time it will send parameter (2,3,0) to the demoMethod. also the order of these three numbers are not important and they must be different .it means that after two times that for loop executes it doesn't send parameter like (1,2,3) and (2,3,1). thanks
public void Points(List<Point> pointList) {
int n = pointList.size();
if (n <= 2) {
System.out.println("null");
} else if (n == 3) {
drawingLine();
} else {
for(int i = 0;i<n;i++){
for(int j = 1;j<=(n-1)*(n-2)*(n-3)/6;j++){
demoMethod(p1,p2,p3);
}
}
}
}
I am not entirely sure what you are trying to do, but if I understand you correctly, you want to do something like this (?):
for(int i = 0;i<n;i++){
for(int j = 1;j<=(n-1)*(n-2)*(n-3)/6;j++){
int p1 = j % 4;
int p2 = (j + 1) % 4;
int p3 = (j + 2) % 4;
demoMethod(p1,p2,p3);
}
}