Java lab question (prime number and between 1)

Source: Internet
Author: User

I used C ++ I wrote a code to determine whether a prime number is a prime number, but today I use JAVA it takes a lot of time. I have to admit myself JAVA too much water, you need to study hard in the future.

the methods in the class are similar to the functions. I will use the methods to do this. Many people use two for loop statement , I think they are not using JAVA Object-oriented thinking, so I insist on using methods.

Here is myCode:

// Declare prime classes

Public class prime {
// Method for determining whether it is a prime number
Public Boolean isprime (INT number ){
For (INT I = 2; I <number; I ++ ){
If (Number % I = 0 ){
Return false;
}
}
Return true;

}
Public static void main (string [] Arg ){
Int n = 10000;
Int sum = 3;

Prime myprime;
Myprime = new prime ();
For (Int J = 3; j <= N; j ++ ){
If (myprime. isprime (j) = true) {// call Method
Sum + = J;
}
}
System. Out. println ("the prime number from 1 to 10000 is:" + sum );
}
}

Result:

The sum of prime numbers from 1 to 10000 is 5736397.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.