Print prime numbers between 0 and 100
Try this one. I have also optimise the code (you only need to check upto sqrt(i) ).
var prime = [];
prime.push(2); //smallest prime
var flag = 0;
for(var i = 3; i < 100; i=i+2) //skip all even no
{
for(var j = 3; j*j <= i; j=j+2) //check by upto sqrt(i), skip all even no
{
if(i % j == 0) {
flag = 0;break; //not a prime, break
}
flag = 1;
}
if (flag == 1) prime.push(i); //prime, add to answer
}
for(var k = 0; k < prime.length; k++)
{
document.writeln(prime[k], "<br>");
}
Print All Prime Numbers Between 1 and 100 using Java-script
This is how you can get the prime numbers without individual checks:
const isPrime = n => [...Array(n).keys()].slice(2).every(divisor => n % divisor !== 0)
const primeNumbers = [...Array(101).keys()].filter(isPrime)
console.log(primeNumbers)
Printing prime numbers from 1 through 100
Three ways:
1.
int main ()
{
for (int i=2; i<100; i++)
for (int j=2; j*j<=i; j++)
{
if (i % j == 0)
break;
else if (j+1 > sqrt(i)) {
cout << i << " ";
}
}
return 0;
}
2.
int main ()
{
for (int i=2; i<100; i++)
{
bool prime=true;
for (int j=2; j*j<=i; j++)
{
if (i % j == 0)
{
prime=false;
break;
}
}
if(prime) cout << i << " ";
}
return 0;
}
3.
#include <vector>
int main()
{
std::vector<int> primes;
primes.push_back(2);
for(int i=3; i < 100; i++)
{
bool prime=true;
for(int j=0;j<primes.size() && primes[j]*primes[j] <= i;j++)
{
if(i % primes[j] == 0)
{
prime=false;
break;
}
}
if(prime)
{
primes.push_back(i);
cout << i << " ";
}
}
return 0;
}
Edit: In the third example, we keep track of all of our previously calculated primes. If a number is divisible by a non-prime number, there is also some prime <= that divisor which it is also divisble by. This reduces computation by a factor of primes_in_range/total_range.
Prime numbers print from range 2...100
One of effective algorithms to find prime numbers is Sieve of Eratosthenes. It is based on idea that you have sorted array of all numbers in given range and you go from the beginning and you remove all numbers after current number divisible by this number which is prime number. You repeat this until you check last element in the array.
There is my algorithm which should do what I described above:
func primes(upTo rangeEndNumber: Int) -> [Int] {
let firstPrime = 2
guard rangeEndNumber >= firstPrime else {
fatalError("End of range has to be greater than or equal to \(firstPrime)!")
}
var numbers = Array(firstPrime...rangeEndNumber)
// Index of current prime in numbers array, at the beginning it is 0 so number is 2
var currentPrimeIndex = 0
// Check if there is any number left which could be prime
while currentPrimeIndex < numbers.count {
// Number at currentPrimeIndex is next prime
let currentPrime = numbers[currentPrimeIndex]
// Create array with numbers after current prime and remove all that are divisible by this prime
var numbersAfterPrime = numbers.suffix(from: currentPrimeIndex + 1)
numbersAfterPrime.removeAll(where: { $0 % currentPrime == 0 })
// Set numbers as current numbers up to current prime + numbers after prime without numbers divisible by current prime
numbers = numbers.prefix(currentPrimeIndex + 1) + Array(numbersAfterPrime)
// Increase index for current prime
currentPrimeIndex += 1
}
return numbers
}
print(primes(upTo: 100)) // [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
print(primes(upTo: 2)) // [2]
print(primes(upTo: 1)) // Fatal error: End of range has to be greater than or equal to 2!
Find prime numbers from a given range of numbers parallel program
I don't have the OMP software installed, so I had to remove the parallelization. However, the code works once the 'print out the prime numbers' loop is adjusted to deal with the fact that the algorithm knows that 2 is the only even prime number and that it stores the primality of an odd number X in isPrime[X / 2]
.
This leads to this code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//#include <omp.h>
static char isPrime[1000];
// odd-only sieve
//static int eratosthenesOdd(int N, int useOpenMP)
static int eratosthenesOdd(int N)
{
/* enable/disable OpenMP */
//omp_set_num_threads(useOpenMP ? omp_get_num_procs() : 1);
/* instead of i*i <= N we write i <= sqr(N) to help OpenMP */
const int NSqrt = (int)sqrt((double)N);
int memorySize = (N - 1) / 2;
int i, j;
/* Let all numbers be prime initially */
//#pragma omp parallel for
for (i = 0; i <= memorySize; i++)
{
isPrime[i] = 1;
}
/* find all odd non-primes */
//#pragma omp parallel for schedule(dynamic)
for (i = 3; i <= NSqrt; i += 2)
{
if (isPrime[i / 2])
{
for (j = i * i; j <= N; j += 2 * i)
{
isPrime[j / 2] = 0;
}
}
}
printf("2\n");
for (int k = 3; k <= N; k += 2)
{
if (isPrime[k / 2] == 1)
{
printf("%d\n", k);
}
}
/* sieve is complete, count primes */
int total = N >= 2 ? 1 : 0;
//#pragma omp parallel for reduction(+:total)
for (i = 1; i <= memorySize; i++)
{
total += isPrime[i];
}
return total;
}
int main(void)
{
//int total = eratosthenesOdd(100, 1);
int total = eratosthenesOdd(100);
printf("Number of primes: %d\n", total);
return 0;
}
And this output:
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
Number of primes: 25
By inspection, this is correct for the primes up to 100.
Related Topics
Two Sets of Parentheses After Function Call
Stop Execution of JavaScript Function (Client Side) or Tweak It
What Does a Tilde Do When It Precedes an Expression
Access Object Child Properties Using a Dot Notation String
How to Get Character Array from a String
How to Get Form Data with JavaScript/Jquery
Constructors in JavaScript Objects
Seedable JavaScript Random Number Generator
Define Global Variable with Webpack
Chrome Desktop Notification Example
Why Variable Hoisting After Return Works on Some Browsers, and Some Not
Remove Objects from Array by Object Property
How to Get Element by Innertext
How to Set Focus on an Input Field After Rendering
How to Write a Named Arrow Function in Es2015
Js Client-Side Exif Orientation: Rotate and Mirror Jpeg Images