程序打印1-100素数,并给出给定范围内复合数字的异常 [英] program to print 1-100 prime number and throw exception for composite number in given range

查看:137
本文介绍了程序打印1-100素数,并给出给定范围内复合数字的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经制作了一个打印1-100个素数的程序。
请帮助我为1到100个数字的复合数字抛出异常。
我是初学者,所以任何帮助将不胜感激。

i have made a program to print 1-100 prime numbers. please help me to throw exception for composite number in range of 1-100 numbers. i am a beginner so any help will be appreciated.

  public static void main(String[] args) {

    System.out.println("Prime numbers from 1 - 100 are :");
    int i = 0;
    int x = 0;

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

        int ctr = 0;
        for (x = i; x >= 1; x--) {
            if (i % x == 0) {
                ctr = ctr + 1;
            }
        }
        if (ctr == 2) {
            System.out.println(i);
        }

    }

}


推荐答案

我宁愿执行 isPrime 方法,并调用它

I'd rather implement isPrime method and call it

public static boolean isPrime(int value) {
  if (value <= 1)
    return false;

  // There's only one even prime: that is two 
  if ((value % 2) == 0) 
    return (value == 2);

  int from = (int) (Math.sqrt(value) + 1);

  // You have to check possible divisors from 3 to sqrt(value)
  for (int i = 3; i <= from; i += 2)
    if ((value % i) == 0)
      return false;

  return true;
}

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

  for (int i = 1; i <= 100; ++i) {
    if (isPrime(i)) 
      System.out.println(i);
    else {
      // i is not prime. You can do nothing, throw an exception etc
      // throw new MyException("Not a prime"); 
    }
  }
}

这篇关于程序打印1-100素数,并给出给定范围内复合数字的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆