Jump to content



Welcome to KnowledgeSutra - Dear Guest , Please Register here to get Your own website. - Ask a Question / Express Opinion / Reply w/o Sign-Up!
- - - - -

Most Efficient Code To Get Prime Numbers


11 replies to this topic

#11 iGuest

    Hail Caesar!

  • Kontributors
  • PipPipPipPipPipPipPipPipPipPipPipPipPipPipPipPipPipPipPipPipPip
  • 5,876 posts
  • Interests:Trap17 Free Web Hosting, No Ads

Posted 22 February 2010 - 06:56 PM

I am so grateful for this site,at least I managed to get an idea of geting primes,as a programmer(beginner) I want to learn how to read and write to files,I do understand that the type of file is determined by the extension on it.For example,files with extension'.Txt' are text files,'.Doc' are word files etc

I want to write a C program that will be able to ceive the different types of numbers and write them in appropiate files.I want to start by using 3 files,file_even for word document,file_odd for text doc and file_prime for an excel file. If I use integersf rom 1 to 250,and write all even files with their halves in file_even so that the every even number is on its own line and a number is separated from its half with a tab,write all odd numberswith  theirs squares in file_odd so that every odd number is on its own line and is separated from its square with a tab,also write all prime numbers and their thirds(rounded to 2 decimal places) in  file_prime and every prime number is on its own lineand a prime number and its third in separate cells(equivalent of of tabs) I wrote a certain code but I want to compare oor even make it better,some help,thanks

-Dense



#12 iikwalsemsiskweyrd

    Newbie [Level 1]

  • Kontributors
  • Pip
  • 10 posts

Posted 03 June 2010 - 02:33 AM

#include <iostream>
#include <cmath>

using namespace std;

bool isPrime( int i );

int main()
{
	for( size_t i = 1; i < 1000; i++ )
	{
		if( isPrime( i ) )
		{
			cout<<i<<endl;
		}
	}

	system( "pause" );
	return 0;
}

bool isPrime( int num )
{
	int limit = sqrt( static_cast<double>(num) );

	if ( num == 2 )
	{
		return true;
	}

	if ( num == 1 || num % 2 == 0 )
	{
		return false;
	}

	for( size_t i = 3; i <= limit; i += 2 )
	{
		if( num % i == 0 )
		{
			return false;
		}
	}

	return true;
}


*system( "pause") was placed for the MSVS console not to automatically close.
*newline at the end of the file if you are compiling with GCC.

Edited by iikwalsemsiskweyrd, 03 June 2010 - 02:41 AM.





Reply to this topic


This post will need approval from a moderator before this post is shown.

  


1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users