finding the next prime number in pascal - primes

I am trying to find the next prime number after the number the user enters in and i have to do it in pascal . I don't even know what to start with , could anyone help me?
program PRIME;
uses crt;
var
C, N : INTEGER;
const
A=2;
Begin PS:
Writeln ('enter your number' ) ;
Read (N);
begin
Writeln(
readln;
End.

You should declare n-element array of bools (primes values are true), where n is a number entered by user and multiplied by two. Then find all primes up to n using sieve of Eratosthenes algorithm (remove all composite numbers changing their values to false). After that, finding next prime number after entered value will be easy. Indexes of true values are prime numbers.
Try to write your own code and then edit your question if it doesn't work.

Two hints:
if the number entered is < 2 then the next prime is 2.
if the number entered is >= 2 then the next prime is an odd number greater than the number entered and less than twice the number entered (Bertrand's Postulate).
No, we won't write your Pascal code for you.

The first step in solving this problem is figuring out how to do it by hand. From wikipedia:
A simple but slow method of verifying the primality of a given number
n is known as trial division. It consists of testing whether n is a
multiple of any integer between 2 and sqrt{n}.
So if you are given 6, you would first test the number 7 to see if it is prime. You test if 7 is prime by dividing all the integer numbers from 2 to the square root of 7(2.645751311). So you have to only test to see if 7 is divisible by 2. If the user enters 14, you have first test to see if 15 is divisible by any of the integer numbers from 2 to the square root of 15 (3.872983346). So you would test to see if 15 is divisible by 2 or 3.
There are two loops involved. One is adding 1 to the input number repeatedly - that is - if they input 10, you test 11 for primeness, then 12, then 13, then 14, then 15, etc. The other loop is dividing all the integer numbers between 2 and the square root of the current number being checked for primeness. Divide it by 2, is there a remainder? Divide by 3, is there a remainder? Divide by 4, is there a remainder? And so on. Each time you get a division with no remainder you can stop that loop since you know that you have not found a prime and need to increment the value and recalculate your square root and start dividing again.
In Free Pascal it looks like this:
program NextPrimeNumber;
uses
Math;
var
user_input : integer;
next_prime : integer;
function CalculateNextPrimeNumber(value : integer) : integer;
var
next_prime_not_found : boolean = true;
square_root : integer = 0;
i : integer = 0;
remainder : integer = 0;
result : integer = 0;
successful_divisions : integer = 0;
begin
(* loop through the numbers above our value till we find one that
is not divisible *)
while next_prime_not_found do
begin
successful_divisions := 0;
value := value + 1;
square_root := trunc(sqrt(value));
(* try and divide by all the numbers between 2 and the square root of
out current number (square root value truncated
to next lowest integer) *)
for i := 2 to square_root do
begin
DivMod(value,i,result,remainder);
if remainder = 0 then
begin
successful_divisions := successful_divisions + 1;
(* this is a non-prime number, so quit trying more divisions *)
break;
end;
end;
if successful_divisions = 0 then
(* we found a prime so stop looking by setting the value
the while loop is checking to false *)
next_prime_not_found := false;
end;
CalculateNextPrimeNumber := value;
end;
begin
writeln('enter a postive number');
readln(user_input);
next_prime := CalculateNextPrimeNumber(user_input);
writeln('the next prime number after ',user_input,' is ',next_prime);
end.

var a,y,i,k:qword;
f:text;
begin
assign(f,'numere.prime');
reset(f);
while not eof(f) do
begin
readln(f,i);
end;
close(f);
repeat
k:=0;
inc(i);
reset(f);
while not eof(f) do
begin
readln(f,a);
if i mod a = 0 then
begin
inc(k);
break;
end;
end;
close(f);
if k=0 then
begin
append(f);
writeln(f,i);
close(f);
end;
until i=10000000;
end.
This program writes all the prime numbers below 10000000 in a file. Later, you can write a new program that checks if the entered number is in that file. (On the first line of the file is '2')

Related

Find minimum prime numbers which sum to a given value

I want to find the minimum set of prime numbers which would sum to a given value e.g. 9 = 7 + 2 (not 3+3+3).
I have already generated a array of prime numbers using sieve of eratosthens
I am traversing the array in descending order to get the array largest prime number smaller than or equal to given number. This works great if the number is odd.
But fails for even numbers e.g 122 = 113 + 7 + 2 but 122 = 109 +13.
From Golbach's Conjecture we know that any even number can be represented as two sum of two prime numbers. So if a number is even we can directly return 2 as output.
But I am trying to figure out a way other than brute force to find minimum prime numbers.
Although your question didn't say so, I assume you are looking for the set of primes that has the smallest cardinality.
If n is even, then consider the primes p in order, 2, 3, 5, …; eventually n - p will be prime, so n is the sum of two primes. This process typically converges very quickly, with the smaller of the two primes seldom larger than 1000 (and usually much smaller than that).
If n is odd, and n - 2 is prime, then n is the sum of the primes 2 and n - 2.
If n is odd, and n - 2 is not prime, then n - 3 is even and can be written as the sum of two primes, as described above.
Thus you can always find two or three primes that sum to any target n greater than 3.
Try this out!
Not an ideal code but if you want to have a working solution :P
primes = [2,3,5,7]
D = 29
i = -1
sum_ = 0
count = 0
while sum_ != D :
sum_ = sum_ + primes[i]
count += 1
if (sum_ == D) :
break
elif D - sum_ == primes[i-1] :
count += 1
break
elif D - sum_ < ex[i-1] and (D-sum_ not in primes) :
sum_ = sum_ - primes[i]
count = count - 1
i = i - 1
print(count)

finding the digit sum in a arthematic sequence

I have a very simple question. I will be provided with the first term of Arithmetic Progression and the common difference. I am required to give sum of digits of all numbers in between the range of L and R.Here the sum means the sum <10 that means for a number say 157, the sum of digits is 1+5+7=13 which is further 1+3=4. The range is the index of the elements. L means the Lth number of that series and L starts from 1.Here L and R can be of range 1 to 10^18. How can i find the sum of these digits for such a large range. I know the digit sum of a number n can be calculated as (n-1)%9+1. But i can't iterate over 10^18 numbers.
Example: let say First term of Arithmetic Progression is 14 and common difference 7.Then the sum of digits of all numbers between 2 and 4 will be sum of (2+1)=3 and (2+8)=(1+0)=1 and (3+5)=8 which is equal to 12
for pattern finding
current=first;
ll arr[10]={0};
while(1)// search for the pattern
{
ll dsum=(current-1)%9+1;// calculating digit sum
if(arr[dsum]!=0)
break;
arr[dsum]=ptr;// saving the value in the array by using hashing
ptr++;
current+=c_diff;
}
for sum
for(ll i=1;i<ptr;i++)
{
sum[i]=sum[i-1]+new_arr[i];
}
Since all of your numbers will be (ultimately) reduced to a single digit, you must be having repetition after certain number of terms, and, that is maximum of 9. (because 10 digits, but 0 not possible to repeat).
So, lets start with an example. Say, a=14, d=7, l=2, r=50. I've changed the value of r from your example.
So, trying to find repetition:
Our repetition array is q (say). Then, 1st term of q is 5 (since 14 = 5).
Now, next term is 21 (= 3). Since 3 is not equal to 5, we continue.
We find all terms till we get 5 again. So, q will be like this in this example:
q[] = {5,3,1,8,6,4,2,9,7} ... and then we have 5 again, so stop.
So, our repetitive pattern has 9 members. Now, find a cumulative sum array with this, which will be like:
sum[] = {5,8,9,17,23,27,29,38,45}
Now, since r=50, find sum of r terms, which will be:
(floor)(50/9) * 45 + sum[50%9]
= 5 * 45 + 23
= 248
Now, similarly, find sum of l-1 terms, (since you have to find sum in range l..r inclusive.
Sum of 1st (2-1) = 1 terms will be:
(floor)(1/9) * 45 + sum[1 % 9]
= 0 + 5
= 5
So, the answer is, 248 - 5 = 243.
well you can solve this problem by taking two arrays of elements 9 and finding the lth term element.
from the lth term find the digit sum of lth element and save it in two array respectively .
w1=a+(l-1)*d
for(i=1,j=w1;i<=9;j+=d,i++){ if(j%9==0){array1[i]=9 ;array2[i]=9;}else{array1[i]=j%9;array2[i]=j%9;}
}
now q = r-l+1
w= q/9 and e=q%9
array1[i]=array1[i]*w // in loop from i= 1 to 9
in array2[i]=0 //new loop from i=e+1 to 9
now digitsum += array1[i]+array2[i] // from a a loop i=1 to 9 and digitsum is the sum of all digit of sequence
this digit sum is solution.

Faster algorithm to count how many numbers are divisible by a specific integer in a range

int a,b,c,d=0;
cin>>a>>b>>c;
for (int i=a;i<=b;i++)
{
if (i%c==0){d++;}
}
cout<<d;
So this is the code, a..b is the number range, c is the divisor, and d counts the multiples of c. For example when a=5, b=15, c=3, d equals 4, because "6, 9, 12, 15" are the multiples between 5 and 15.
I need to find faster way to do this, can anyone help?
One way is to do it like this (no loops required):
int lower = (a + c - 1) / c; // find lowest divisor (round up)
int upper = b / c; // find higher divisor (round down)
d = upper - lower + 1; // get no of divisors
For your example case, lower will be 2, upper will be 5, giving d equal to 4.
Rather than checking every number within the range you could something like this.
Find number of divisors within the maximum number and then within minimum number. After subtraction you would get desired result. For e.g:-
Let's say range is [5,15].
15/3 = 5; //within max number.
5/3 = 1; //within min number.
result = 5-1 = 4;
NOTE:- You have to take care of boundaries in the range to get correct result.
An untested off-the-top-of-my-head algorithm to find all the proper divisors of a positive integer...
Let the number you want to find the divisors for be N.
Let i = 2
If N % i == 0, then you have two divisors: i and N/i. Add these to the list (or count) of divisors
If i > sqrt(N), finish, else set i = i + 1 and go to (2)
For example, if N = 24, then this would give you
i = 2 => 2, 12
i = 3 => 3, 8
i = 4 => 4, 6
sqrt(24) = 4.90, so finish
(I know this algorithm doesn't strictly match what you asked, but it should be easy enough to adapt.)

need help about sieve of eratosthenes in free pascal

my teacher gave me this :
n<=10^6;
an array of n integer :ai..an(ai<=10^9);
find all prime numbers .
he said something about sieve of eratosthenes,and I read about it,also the wheel factorization too,but I still couldn't figure it out how to get the program (fpc) to run in 1s.??
as I know it's impossible,but still want to know your opinion .
and with the wheel factorization ,a 2*3 circle will treat 25 as a prime number,and I wanna ask if there is a way to find out the first number of the wheel treated wrong as a prime number.
example:2*3*5 circle ,how to find the first composite number treated as aprime number??
please help..and sorry for bad english.
A proper Sieve of Eratosthenes should find the primes less than a billion in about a second; it's possible. If you show us your code, we'll be happy to help you find what is wrong.
The smallest composite not marked by a 2,3,5-wheel is 49: the next largest prime not a member of the wheel is 7, and 7 * 7 = 49.
I did it now and it's finding primes up to 1000000 in a few milliseconds, without displaying all those numbers.
Declare an array a of n + 1 bools (if it is zero-based). At the beginning 0th and 1st element are false, all others are true (false is not a prime).
The algorithm looks like that:
i = 2;
while i * i <= n
if a[i] == true
j = i * i;
while j < n
a[j] = false;
j = j + i;
i = i + 1;
In a loop the condition is i * i <= n because you start searching from i * i (smaller primes than that was found already by one of other primes) so square root of i must not be bigger than n. You remove all numbers which are multiplies of primes up to n.
Time complexity is O(n log log n).
If you want to display primes, you display indexes which values in array are true.
Factorization is usefull if you want to find e.g. all semiprimes from 0 to n (products of two prime numbers). Then you find all smallest prime divisors from 0 to n/2 and check for each number if it has prime divisor and if number divided by its prime divisor has zero divisors. If so - it is a semiprime. My program wrote like that was calculating 8 times faster than first finding all primes and then multiplying them and saving result in an array.

Write an algorithm to return the prime numbers of an integer, for example if your input is 10 the output is list a with elements 2 and 5

this one i get as assignment in discrete maths.
i try to do like this.
procedure prime_numbers (x)
n:= 1
for i:= to n<=x do
n mod i=1 then
return (prime)
end prime_number.
What you are looking for is called "prime number factorisation".
On http://www.btinternet.com/~se16/js/factor.htm you find an example in JavaScript.
Finding the prime factors of a given number is a hard problem. When the numbers are very large, no efficient factorization algorithm is known. But here's a simple algorithm to find the prime factors of a relatively small number N:
list all the prime numbers in the range 2...N.
for each prime number p in the list, check if N mod p is 0. If so, p is a (prime) factor of N.
How to list all the prime numbers in the range 2...N?
We'll start with an empty list and fill it with prime numbers:
for n=2...N:
foreach p in your list:
if n mod p is 0 then continue
insert n to the list
Note that this is a very simple algorithm and there are many algorithms which are much better. If you need a more clever solution check out Dixon's algorithm or the Quadratic Sieve algorithm.
A better (but less triavial) way to list all the prime numbers up to N is the Sieve of Eratosthenes.
Some bugs in your algorithm:
You probably meant to write "n mod i = 0", not "n mod i = 1". "n mod i = 0" is equivalen to "n is divisible by i" or "i is a factor of n".
What your algorithm finds is all the factors of n while what you need to find is all the prime factors of n.
If you can generate prime numbers, you can do prime factorization. The only trouble is that it's unavoidably slow.
A simple way is to use the traditional seive of eratosthenes to generate the prime numbers. For each prime generated (in increasing order), repeatedly check whether it divides your number. Each time it does, accept it as a factor and replace your number with the result from the division. When you can't divide any more, move on to the next prime.
So if your number were 20, you'd first try prime 2.
20/2 = 10, so accept factor 2 and use number 10
10/2 = 5, so accept factor 2 and use number 5
5/2 = 2 rem 1, so move onto prime 3
5/3 = 1 rem 2, so move onto prime 5
5/5 = 1, so accept factor 5 and use number 1
When you reduce your remaining number to 1, you end.
//Copyright 1998 Henry Bottomley (written 23 December)
//All rights reserved
function factorise(numm) // To calculate the prime factors of a number
{
var newnum = numm; // Initialise
var newtext = "";
var checker = 2; // First possible factor to check
while (checker*checker <= newnum) // See if it is worth looking further for factors
{
if (newnum % checker == 0) // If the possible factor is indeed a factor...
{
newtext = newtext + checker; // ...then record the factor
newnum = newnum/checker; // and divide by it
if (newnum != 1) // then check whether it is not last...
{
newtext = newtext + "."; // ...and if so prepare for the next
}
}
else // otherwise...
{
checker++; // try the next possible factor
}
}
if (newnum != 1) // If there is anything left at the end...
{ // ...this must be the last prime factor
newtext = newtext + newnum; // so it too should be recorded
}
if (newtext == "" + numm) // If the only prime factor is the original...
{
newtext = "Prime: " + newtext; // ...then note that it must have been prime.
}
return newtext; // Return the prime factors
}