Given two integers A and B and an integer N. The task is to find out N prime numbers of the form A + nB or B + nA( n=1, 2, 3…). If it is not possible, print -1.
Input: A = 3, B = 5, N = 4
Output: 13, 11, 17, 23
Input: A = 4, B = 6, N = 4
Since A + nB to be a prime one thing is sure that there should not present any common factor between A and B, means A and B should be co-prime.
The best and most efficient approach will be to use Dirichlet’s Theorem.
Dirichlet’s Theorem says that if a and b are relatively prime positive integers, then the arithmetic sequence a, a+b, a+2b, a+3b…contains infinitely many primes.
So firstly check if A and B are co-prime.
If A and B are co-prime then check A+nB and B+nA for their primality where n=1, 2, 3…. Print the first N prime numbers among them.
Below is the implementation of the above approach:
11 13 17 23
- Find three prime numbers with given sum
- Find the XOR of first N Prime Numbers
- Find two prime numbers with given sum
- Find product of prime numbers between 1 to n
- Find the sum of prime numbers in the Kth array
- Program to find sum of prime numbers between 1 to n
- Find the Product of first N Prime Numbers
- Find count of Almost Prime numbers from 1 to N
- Program to find the LCM of two prime numbers
- Absolute difference between the Product of Non-Prime numbers and Prime numbers of an Array
- Find all the prime numbers of given number of digits
- Program to find Prime Numbers Between given Interval
- Find two distinct prime numbers with given product
- Find the prime numbers which can written as sum of most consecutive primes
- Find a sequence of N prime numbers whose sum is a composite number
- Absolute Difference between the Sum of Non-Prime numbers and Prime numbers of an Array
- Absolute difference between the XOR of Non-Prime numbers and Prime numbers of an Array
- Find the highest occurring digit in prime numbers in a range
- Check if a number is Prime, Semi-Prime or Composite for very large numbers
- Print the nearest prime number formed by adding prime numbers to N
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.