Find all primes/composite (sum) within 1000, Java algorithm (23 lines) __ algorithm

Source: Internet
Author: User

This is basically the simplest way, there should be no one, hehe ~

According to the definition of prime numbers: only 1 and himself are divisible. 1 is not prime.

Write down the following code and run it correctly.

Remove the annotation and find out the number of all primes within 1000.

Class FindAll 
{
	//static int sum=0;
	static void find (int i)
	{
		int t=0;
		for (int k=1;k<=1000;k++)
		{
			if (i%k!=0)
			t++;
			if (t==998)
			System.out.println (i);
			Sum+=i
		}
	}
	public static void Main (string[] args) 
	{for
		(int i=0;i<=1000;i++)
		{
			if (i==1)
			continue;
			Find (i);
		}
		SYSTEM.OUT.PRINTLN (sum);
	}

The following code is the code that asks for a composite, and the logic is: if a number can be rounded by at least 3 digits, then he is a composite.

Also, remove the annotation to find the sum of all composite numbers within 1000.

Class FindAll 
{
	//static int sum=0;
	static void find (int i)
	{
		int t=0;
		for (int k=1;k<=1000;k++)
		{
			if (i%k==0)
			t++;
			if (t==3)
				{			
					System.out.println (i);
					sum+=i;
					break;
				}
	}} public static void Main (string[] args) 
	{for
		(int i=0;i<=1000;i++)
		{find						
			(i);
		}
		SYSTEM.OUT.PRINTLN (sum);
	}



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.