Find Nth number of the series 1, 6, 15, 28, 45, …..
Last Updated :
30 Aug, 2022
Given the first two numbers of a series. The task is to find the Nth( N may be up to 10^18) number of that series.
Note: Every Element in the array is two less than the mean of the number preceding and succeeding of it. The answer can be very large so print answer under modulo 10^9+9.
Examples:
Input: N = 3
Output: 15
(1 + 15)/2 - 2 = 6
Input: N = 4
Output: 28
(6 + 28)/2 - 2 = 15
Observation: According to the statement, the series formed will be 1, 6, 15, 28, 45….. So, the formula for Nth term will be:
2*n*n - n
C++
#include <bits/stdc++.h>
using namespace std;
#define mod 1000000009
int NthTerm( long long n)
{
long long x = (2 * n * n) % mod;
return (x - n + mod) % mod;
}
int main()
{
long long N = 4;
cout << NthTerm(N);
return 0;
}
|
C
#include <stdio.h>
#define mod 1000000009
int NthTerm( long long n)
{
long long x = (2 * n * n) % mod;
return (x - n + mod) % mod;
}
int main()
{
long long N = 4;
printf ( "%d" ,NthTerm(N));
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG {
static long NthTerm( long n)
{
long x = ( 2 * n * n) % 1000000009 ;
return (x - n + 1000000009 ) % 1000000009 ;
}
public static void main(String args[])
{
long N = 4 ;
System.out.println(NthTerm(N));
}
}
|
Python
def NthTerm(N) :
x = ( 2 * N * N) % 1000000009
return ((x - N + 1000000009 ) % 1000000009 )
if __name__ = = "__main__" :
N = 4
print (NthTerm(N))
|
C#
using System;
class GFG
{
static long NthTerm( long n)
{
long x = (2 * n * n) % 1000000009;
return (x - n + 1000000009) %
1000000009;
}
public static void Main()
{
long N = 4;
Console.WriteLine(NthTerm(N));
}
}
|
PHP
<?php
$mod = 1000000009;
function NthTerm( $n )
{
global $mod ;
$x = (2 * $n * $n ) % $mod ;
return ( $x - $n + $mod ) % $mod ;
}
$N = 4;
echo NthTerm( $N );
?>
|
Javascript
<script>
function NthTerm(n) {
var x = (2 * n * n) % 1000000009;
return (x - n + 1000000009) % 1000000009;
}
var N = 4;
document.write(NthTerm(N));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...