Dado un número entero N , la tarea es calcular la suma de todos los i de 1 a N tal que (2 i + 1) % 3 = 0 .
Ejemplos:
Entrada: N = 3
Salida: 4
Para i = 1, 2 1 + 1 = 3 es divisible por 3.
Para i = 2, 2 2 + 1 = 5 que no es divisible por 3.
Para i = 3, 2 3 + 1 = 9 es divisible por 3.
Por lo tanto, sum = 1 + 3 = 4 (para i = 1, 3)Entrada: N = 13
Salida: 49
Enfoque: Si observamos cuidadosamente, i siempre será un número impar, es decir , 1, 3, 5, 7, ….. . Usaremos la fórmula para la suma de los primeros n números impares que es n * n .
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; // Function to return the required sum int sumN(int n) { // Total odd numbers from 1 to n n = (n + 1) / 2; // Sum of first n odd numbers return (n * n); } // Driver code int main() { int n = 3; cout << sumN(n); return 0; }
Java
// Java implementation of the approach class GFG { // Function to return the required sum static int sum(int n) { // Total odd numbers from 1 to n n = (n + 1) / 2; // Sum of first n odd numbers return (n * n); } // Driver code public static void main(String args[]) { int n = 3; System.out.println(sum(n)); } }
Python3
# Python3 implementation of the approach # Function to return the required sum def sumN(n): # Total odd numbers from 1 to n n = (n + 1) // 2; # Sum of first n odd numbers return (n * n); # Driver code n = 3; print(sumN(n)); # This code is contributed by mits
C#
// C# implementation of the approach using System; public class GFG { // Function to return the required sum public static int sum(int n) { // Total odd numbers from 1 to n n = (n + 1) / 2; // Sum of first n odd numbers return (n * n); } // Driver code public static void Main(string[] args) { int n = 3; Console.WriteLine(sum(n)); } } // This code is contributed by Shrikant13
PHP
<?php // PHP implementation of the approach // Function to return the required sum function sumN($n) { // Total odd numbers from 1 to n $n = (int)(($n + 1) / 2); // Sum of first n odd numbers return ($n * $n); } // Driver code $n = 3; echo sumN($n); // This code is contributed by mits ?>
Javascript
<script> // Javascript implementation of the approach // Function to return the required sum function sumN(n) { // Total odd numbers from 1 to n n = parseInt((n + 1) / 2); // Sum of first n odd numbers return (n * n); } // Driver code var n = 3; document.write(sumN(n)); // This code is contributed by noob2000. </script>
Producción
4
Tiempo Complejidad: O(1)
Espacio Auxiliar: O(1)