Generate a list of n consecutive composite numbers (An interesting method)
Given a number n, generate a list of n composite numbers.
Examples:
Input : 5
Output : 122, 123, 124, 125
Input : 10
Output : 3628802, 3628803, 3628804, 3628805, 3628806,
3628807, 3628808, 3628809, 3628810
The idea here is using the properties of . Since , then numbers , all divide . Therefore is divisible by 2, is divisible by 3 ….. is divisible by n. And by above pattern they are consecutive composites.
We find (n+1)!, then we print numbers (n+1)! + 2, (n+1)! + 3, …. (n+1)! + (n + 1).
Below is the implementation of above approach:
C++
#include <iostream>
using namespace std;
unsigned long long int factorial(unsigned int n)
{
unsigned long long int res = 1;
for ( int i=2; i<=n; i++)
res *= i;
return res;
}
void printNComposite( int n)
{
unsigned long long int fact = factorial(n+1);
for ( int i = 2; i <= n+1; ++i)
cout << fact + i << " " ;
}
int main()
{
int n = 4;
printNComposite(n);
return 0;
}
|
Java
class GFG {
static long factorial( int n) {
long res = 1 ;
for ( int i = 2 ; i <= n; i++) {
res *= i;
}
return res;
}
static void printNComposite( int n) {
long fact = factorial(n + 1 );
for ( int i = 2 ; i <= n + 1 ; ++i) {
System.out.print(fact + i + " " );
}
}
public static void main(String[] args) {
int n = 4 ;
printNComposite(n);
}
}
|
Python3
def factorial( n):
res = 1 ;
for i in range ( 2 , n + 1 ):
res * = i;
return res;
def printNComposite(n):
fact = factorial(n + 1 );
for i in range ( 2 , n + 2 ):
print (fact + i, end = " " );
n = 4 ;
printNComposite(n);
|
C#
using System;
public class Program{
static long factorial( int n) {
long res = 1;
for ( int i = 2; i <= n; i++) {
res *= i;
}
return res;
}
static void printNComposite( int n) {
long fact = factorial(n + 1);
for ( int i = 2; i <= n + 1; ++i) {
Console.Write(fact + i + " " );
}
}
public static void Main() {
int n = 4;
printNComposite(n);
}
}
|
PHP
<?php
function factorial( $n )
{
$res = 1;
for ( $i = 2; $i <= $n ; $i ++)
$res *= $i ;
return $res ;
}
function printNComposite(int $n )
{
$fact = factorial( $n + 1);
for ( $i = 2; $i <= $n + 1; ++ $i )
echo $fact + $i , " " ;
}
$n = 4;
printNComposite( $n );
?>
|
Javascript
<script>
function factorial(n) {
let res = 1;
for (let i = 2; i <= n; i++) {
res *= i;
}
return res;
}
function printNComposite(n) {
let fact = factorial(n + 1);
for (let i = 2; i <= n + 1; ++i) {
document.write(fact + i + " " );
}
}
let n = 4;
printNComposite(n);
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
The above solution causes overflow very soon (for small values of n). We can use technique to find factorial of large number to avoid overflow.
Last Updated :
06 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...