I made a primality test program in Java


This post is for beginners to learn Java by themselves and write a program through trial and error with original ideas (while investigating a little), and publishes code that is not helpful at all with self-satisfaction. It is something to do.

At the same time as watching the growth of beginners with warm eyes, I think that there are naturally places where you may have the opinion "No, this is strange (# ゚ Д ゚) !?", so feel free to comment in that case. please.

About posting on Qiita

This is the second post. Looking back at the sentence I posted the other day, I misunderstood that the description method in Qiita was HTML format, but there is a Markdown description method, and this time I would like to write it in this way. Thank you very much for your professor m (_ _) m I hope it will be easier to see.

Primality test program described in the interview

(* When I went home and compiled it, an error occurred, so I will post the corrected version.) (* I also use the Random class, but I learned this recently, so I tried using it for a while.)

The other day, I was asked to make a primality test program using Java, and I wrote the following code with a doy face.

System.out.println("Random primality test program");
java.util.Random rm = new java.util.Random();
int s = rm.nextInt(100);

if (s == 2 || s == 3) {
    System.out.println(s + "Is a prime number");
} else if (s % 2 == 0 || s % 3 == 0) {
    System.out.println(s + "Is not a prime number");
} else {
    System.out.println(s + "Is a prime number");

(Aside from the tsukkomi that the code is dirty)

** First of all, you didn't know the "definition of prime numbers". ** **

(I like this kind of math problem because I am a liberal arts student, but I remember the formulas and so on beyond the universe.)

According to Wikipedia teacher

"A prime number is a natural number that has no divisors other than the trivial positive divisors (1 and itself) and is not 1. 』\

Well the point is

** I think that a natural number that can only be divided by the number itself and 1 is a prime number, and if it is divisible by another number, it is not a prime number. ** **

For example, it seems to be infinitely springing up like 2,3,5,7,11.

If I explain the above program a little, I can compile it without any error, but even numbers that are not prime numbers are judged to be prime numbers.

Such a program is made from the idea that if n is divisible by 2, it is an even number, and if n is divisible by 3, n is an odd number.

However, for example, 121 is the square of 11, so it is not a prime number, but it is not divisible by 2 or 3, so it is judged as a prime number.

(It's a little embarrassing at the level of starting over from the first year of high school.)

Primality test program

System.out.println("Primality test program");
int v = 123;
System.out.println("The entered number is "" + v + ""is");

if (v < 2) {
    System.out.println("A number less than 2 has been entered");
} else if (v == 2) {
    System.out.println(v + "Is a prime number");
} else {
    boolean issosu = true;
    for (int u = 2; u < v; u++) {
        if (v % u == 0) {
            is = false;

    if (isSosu) {
        System.out.println(v + "Is a prime number");
    } else {
        System.out.println(v + "Is not a prime number");

(Aside from the tsukkomi that the code is dirty)

I'm afraid this will correctly determine the prime number, but it took two days to complete. I talked with my younger brother about what kind of numbers are prime numbers, and if it is divisible by 2, it is an even number, and from the other numbers, a natural number that is not the square of a certain number is a prime number. Here is the answer that came out while relying on the net search

"** n that is not divisible by numbers less than natural number n is a prime number **"

In addition to this

"** n is a prime number if n is 2, error ** if n is less than 2"

After limiting n to numbers larger than 2 in advance, it is completed by creating a program that determines that "numbers that are not divisible by n> v" or "numbers that are not divisible by n> = n-1" are prime numbers. did.

However, if you simply use the for statement,

5 is not a prime number 5 is not a prime number 5 is a prime number 5 is not a prime number 5 is not a prime number . . . I started to judge whether 5 (the number I entered) was a prime number with the number expressed in the for statement, and I struggled hard.

Well, I didn't know how to solve it, so I googled it a bit, but I defined the variable isSosu as a boolean type and set the initial value to true. Then, in the for statement, u is looped between numbers 1 less than v, and if u% v == 0, u is divisible by a natural number smaller than its own number. Substitute false for isSosu. By doing this, if it is divisible, it is false, and in other cases it can be considered again, and if (isSosu) {... and true case can be System.out.println. did. (Hmm, this is hard to understand.)

It was regrettable that I couldn't make it completely by myself because I couldn't pay attention to using boolean type and I googled it, but if a beginner builds a primality test program with the knowledge of an introductory book, this is I wonder if it will be like this, but I think there is probably a better and more efficient way to write it. I'm not good at math, and I haven't written much Java programs yet.

So, for the time being, I think that being able to write this primality test program is one of the barriers as proof when it is tested whether the program can be assembled. I think that a beginner will solve some problems when creating a program, but one of the answers is like this. I hope you can read it as if you want to see it. I think.

Recommended Posts

I made a primality test program in Java
I wrote a primality test program in Java
[Beginner] I made a program to sell cakes in Java
I made a rock-paper-scissors game in Java (CLI)
I wrote a prime factorization program in Java
I made roulette in Java.
I made a simple calculation problem game in Java
Ruby: I made a FizzBuzz program!
I created a PDF in Java.
I made a shopify app @java
I made an annotation in Java.
Primality test Java
I made a new Java deployment tool
I made a program in Java that solves the traveling salesman problem with a genetic algorithm
I made a Diff tool for Java files
I wanted to make (a == 1 && a == 2 && a == 3) true in Java
I made a Ruby extension library in C
I tried to create a Clova skill in Java
I tried to make a login function in Java
I made a Restful server and client in Spring.
What I learned when building a server in Java
I made a Wrapper that calls KNP from Java
Call a program written in Swift from Processing (Java)
I made a chat app.
Fastest Primality Test C # Java C ++
Find a subset in Java
Null-safe program in Java (Eclipse)
I tried metaprogramming in Java
I just wanted to make a Reactive Property in Java
Even in Java, I want to output true with a == 1 && a == 2 && a == 3
I tried to convert a string to a LocalDate type in Java
I investigated Randoop, a JUnit test class generator for Java
I tried to make a client of RESAS-API in Java
[Personal development] I made a site to recruit test users!
I made a Dockerfile to start Glassfish 5 using Oracle Java
I made a JAVA framework "numatrix" that easily generates unique numbers in a distributed environment & multithreading.
Implement Table Driven Test in Java 14
I sent an email in Java
3 Implement a simple interpreter in Java
I made a GUI with Swing
I wrote Goldbach's theorem in java
A simple sample callback in Java
I made a simple recommendation function.
Create a Servlet program in Eclipse
I tried using JWT in Java
Age guessing game made in Java
Get stuck in a Java primer
I made a matching app (Android app)
Sample vending machine made in Java
I made a package.xml generation tool.
[Android] I made a pedometer app.
I made the "Sunshine Ikezaki game" I saw on Twitter in Java.
Do I need a test if I do DDD in a language with types?
I can't create a Java class with a specific name in IntelliJ
[Note] What I learned in half a year from inexperienced (Java)
[Note] What I learned in half a year from inexperienced (Java) (1)
I passed the Java test level 2 so I will leave a note
I recently made a js app in the rumored Dart language
I wrote a Stalin sort that feels like a mess in Java
I made a method to ask for Premium Friday (Java 8 version)
I wrote a route search program in TDD and refactored it