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
- Print numbers such that no two consecutive numbers are co-prime and every three consecutive numbers are co-prime
- Check if there exists a number with X factors out of which exactly K are prime
- Absolute Difference between the Sum of Non-Prime numbers and Prime numbers of an Array
- Absolute difference between the Product 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
- Count prime numbers that can be expressed as sum of consecutive prime numbers
- Find out the correct position of the ball after shuffling
- Find out the minimum number of coins required to pay total amount
- Prime numbers after prime P with sum S
- Print the nearest prime number formed by adding prime numbers to N
- Check if a prime number can be expressed as sum of two Prime Numbers
- Print prime numbers with prime sum of digits in an array
- Print all numbers whose set of prime factors is a subset of the set of the prime factors of X
- Sum of prime numbers without odd prime digits
- Check if a number is Prime, Semi-Prime or Composite for very large numbers
- Permutation of first N positive integers such that prime numbers are at prime indices
- Permutation of first N positive integers such that prime numbers are at prime indices | Set 2
- Count all prime numbers in a given range whose sum of digits is also prime
- Count numbers in a given range whose count of prime factors is a Prime Number
- Quick ways to check for Prime and find next Prime in Java
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.