P
P
PRAIT2019-07-05 12:53:18
Java
PRAIT, 2019-07-05 12:53:18

Using a loop to display all prime numbers from 1 to 100 how why does it come out true?

Hello everyone, there is a task, you need to use cycles to display all prime numbers from 1 to 100 on the screen. A prime number is a number that is only divisible by one or by itself.
Here is the code:

import java.util.Scanner;

public class Test {

  public static void main(String[] args) {
    try (Scanner tru = new Scanner(System.in)) {
      int number;
      System.out.println("Enter number");

      for (int i = 2; i <= 100; i++) {
        System.out.println(i % 1 == 0 || i % i == 0);
      }
    }
  }
}

Guys, why when executing the program it just outputs
true
true
true
true
true...
Do I need to translate it into a number somehow or is the program implemented incorrectly? Thank you!

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Developer, 2019-07-05
@PRAIT

The program is incorrect.
Make another cycle inside this main one.

for (int i = 2; i <= 100; i++) {
bool isPrime = i > 2;
for (int j = 2; j < i; j++) {
        if(i % j == 0){ isPrime = false;
break;}
      }
if(isPrime)
        System.out.println(i);
      }

The code is suboptimal, O(n^2), but it will do for you

G
GavriKos, 2019-07-05
@GavriKos

The program is not implemented correctly. You do not display a number, but the result of checking whether the number is prime.
Rewrite using if.

C
Cheypnow, 2019-07-05
@Cheypnow

The System.out.println(i % 1 == 0 || i % i == 0);result of the check is displayed, not the number itself.
And you need to display the result if the check is successful:

if (i % 1 == 0 || i % i == 0) {
    System.out.println(i);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question