当前位置: 代码迷 >> J2SE >> 求援!为什么输出素数会有9,27这些,还少了2
  详细解决方案

求援!为什么输出素数会有9,27这些,还少了2

热度:323   发布时间:2016-04-24 18:08:55.0
求助!!!为什么输出素数会有9,27这些,还少了2?
import java.util.Scanner;
public class Primes
{
  public void primes()
  {
  System.out.println("请输入一个整数:");
  Scanner sc = new Scanner(System.in);
  int a = sc.nextInt();
  for(int i=2;i<=a;i++)
  {  
  for(int j=2;j<i;j++)
  {
  if(i%j==0)
  {
  break;
  }
  else
  {
  System.out.print(i+"\t");
  break;
  }
  }
   
  }
  }
  public static void main(String args[])
  {
  Primes p = new Primes();
  p.primes();  
  }
}

------解决方案--------------------
Java code
package com.c813;import java.util.Scanner;public class Primes {    public void primes() {        System.out.println("请输入一个整数:");        Scanner sc = new Scanner(System.in);        int a = sc.nextInt();        for (int i = 2; i <= a; i++) {            boolean b = true;            for (int j = 2; j < i; j++) {                if (i == 2) {                    break;                }                if (i % j == 0) {                    b = false;                }            }            if (b == true) {                System.out.println(i + "  ");            }        }    }    public static void main(String args[]) {        Primes p = new Primes();        p.primes();    }}
  相关解决方案