Dado un número entero N , la tarea es encontrar la suma de los primeros N números naturales con signos alternos, es decir, 1 – 2 + 3 – 4 + 5 – 6 + ….
Ejemplos:
Entrada: N = 6
Salida: -3
Explicación:
1 – 2 + 3 – 4 + 5 – 6 = -3
Por lo tanto, la salida requerida es -3.Entrada: N = 5
Salida: 3
Explicación:
1 – 2 + 3 – 4 + 5 = 3
Por lo tanto, la salida requerida = 3
Enfoque ingenuo: siga los pasos a continuación para resolver el problema:
- Inicialice una variable, diga alternateSum para almacenar la suma del signo alternativo de los primeros N números naturales.
- Itere sobre el rango [1, N] usando la variable i y verifique si i es par o no . Si se determina que es cierto, actualice la suma alternativa += -i .
- De lo contrario, actualice alternateSum += i .
- Finalmente, imprima el valor de alternateSum .
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ program to implement // the above approach #include <bits/stdc++.h> using namespace std; // Function to find the sum of first // N natural numbers with alternate signs int alternatingSumOfFirst_N(int N) { // Stores sum of alternate sign // of first N natural numbers int alternateSum = 0; for (int i = 1; i <= N; i++) { // If is an even number if (i % 2 == 0) { // Update alternateSum alternateSum += -i; } // If i is an odd number else { // Update alternateSum alternateSum += i; } } return alternateSum; } // Driver Code int main() { int N = 6; cout<<alternatingSumOfFirst_N(N); return 0; }
Java
// Java program to implement // the above approach import java.util.*; class GFG{ // Function to find the sum of first // N natural numbers with alternate signs static int alternatingSumOfFirst_N(int N) { // Stores sum of alternate sign // of first N natural numbers int alternateSum = 0; for(int i = 1; i <= N; i++) { // If is an even number if (i % 2 == 0) { // Update alternateSum alternateSum += -i; } // If i is an odd number else { // Update alternateSum alternateSum += i; } } return alternateSum; } // Driver Code public static void main(String[] args) { int N = 6; System.out.print(alternatingSumOfFirst_N(N)); } } // This code is contributed by Amit Katiyar
Python3
# Python3 program to implement # the above approach # Function to find the sum of # First N natural numbers with # alternate signs def alternatingSumOfFirst_N(N): # Stores sum of alternate sign # of First N natural numbers alternateSum = 0 for i in range(1, N + 1): # If is an even number if (i % 2 == 0): # Update alternateSum alternateSum += -i # If i is an odd number else: alternateSum += i return alternateSum # Driver Code if __name__ == "__main__" : N = 6 print(alternatingSumOfFirst_N(N)) # This code is contributed by Virusbuddah_
C#
// C# program to implement // the above approach using System; class GFG{ // Function to find the sum of first // N natural numbers with alternate signs static int alternatingSumOfFirst_N(int N) { // Stores sum of alternate sign // of first N natural numbers int alternateSum = 0; for(int i = 1; i <= N; i++) { // If is an even number if (i % 2 == 0) { // Update alternateSum alternateSum += -i; } // If i is an odd number else { // Update alternateSum alternateSum += i; } } return alternateSum; } // Driver Code public static void Main(String[] args) { int N = 6; Console.Write(alternatingSumOfFirst_N(N)); } } // This code is contributed by 29AjayKumar
Javascript
<script> // Javascript program to implement // the above approach // Function to find the sum of first // N natural numbers with alternate signs function alternatingSumOfFirst_N(N) { // Stores sum of alternate sign // of first N natural numbers var alternateSum = 0; for (i = 1; i <= N; i++) { // If is an even number if (i % 2 == 0) { // Update alternateSum alternateSum += -i; } // If i is an odd number else { // Update alternateSum alternateSum += i; } } return alternateSum; } // Driver Code var N = 6; document.write(alternatingSumOfFirst_N(N)); // This code is contributed by Rajput-Ji </script>
-3
Complejidad temporal: O(N)
Espacio auxiliar: O(1)
Enfoque eficiente: Para optimizar el enfoque anterior, la idea se basa en las siguientes observaciones:
Si N es un número par, la suma de los signos alternos de los primeros N números naturales es = (-N) / 2.
Si N es un número impar, la suma de los signos alternos de los primeros N números naturales es = (N + 1) / 2.
Siga los pasos a continuación para resolver el problema:
- Inicialice una variable, diga alternateSum para almacenar la suma del signo alternativo de los primeros N números naturales.
- Comprueba si N es un número par o no . Si se determina que es cierto, actualice la suma alternativa = (-N) / 2 .
- De lo contrario, actualice alternateSum = (N + 1) / 2 .
- Finalmente, imprima el valor de alternateSum .
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ program to implement // the above approach #include <bits/stdc++.h> using namespace std; // Function to find the sum of first // N natural numbers with alternate signs int alternatingSumOfFirst_N(int N) { // Stores sum of alternate sign // of first N natural numbers int alternateSum = 0; // If N is an even number if (N % 2 == 0) { // Update alternateSum alternateSum = (-N) / 2; } // If N is an odd number else { // Update alternateSum alternateSum = (N + 1) / 2; } return alternateSum; } // Driver Code int main() { int N = 6; cout<<alternatingSumOfFirst_N(N); return 0; }
Java
// Java program to implement // the above approach import java.util.*; class GFG { // Function to find the sum of first // N natural numbers with alternate signs static int alternatingSumOfFirst_N(int N) { // Stores sum of alternate sign // of first N natural numbers int alternateSum = 0; // If N is an even number if (N % 2 == 0) { // Update alternateSum alternateSum = (-N) / 2; } // If N is an odd number else { // Update alternateSum alternateSum = (N + 1) / 2; } return alternateSum; } // Driver Code public static void main(String[] args) { int N = 6; System.out.print(alternatingSumOfFirst_N(N)); } } // This code is contributed by 29AjayKumar
Python3
# Python program to implement # the above approach # Function to find the sum of first # N natural numbers with alternate signs def alternatingSumOfFirst_N(N): # Stores sum of alternate sign # of first N natural numbers alternateSum = 0; # If N is an even number if (N % 2 == 0): # Update alternateSum alternateSum = (-N) // 2; # If N is an odd number else: # Update alternateSum alternateSum = (N + 1) // 2; return alternateSum; # Driver Code if __name__ == '__main__': N = 6; print(alternatingSumOfFirst_N(N)); # This code contributed by shikhasingrajput
C#
// C# program to implement // the above approach using System; class GFG { // Function to find the sum of first // N natural numbers with alternate signs static int alternatingSumOfFirst_N(int N) { // Stores sum of alternate sign // of first N natural numbers int alternateSum = 0; // If N is an even number if (N % 2 == 0) { // Update alternateSum alternateSum = (-N) / 2; } // If N is an odd number else { // Update alternateSum alternateSum = (N + 1) / 2; } return alternateSum; } // Driver Code public static void Main(String[] args) { int N = 6; Console.Write(alternatingSumOfFirst_N(N)); } } // This code is contributed by 29AjayKumar
Javascript
<script> // Javascript program to implement // the above approach // Function to find the sum of first // N natural numbers with alternate signs function alternatingSumOfFirst_N(N) { // Stores sum of alternate sign // of first N natural numbers var alternateSum = 0; // If N is an even number if (N % 2 == 0) { // Update alternateSum alternateSum = (-N) / 2; } // If N is an odd number else { // Update alternateSum alternateSum = (N + 1) / 2; } return alternateSum; } // Driver Code var N = 6; document.write(alternatingSumOfFirst_N(N)); // This code contributed by Rajput-Ji </script>
-3
Tiempo Complejidad: O(1)
Espacio Auxiliar: O(1)
Publicación traducida automáticamente
Artículo escrito por karangargabc y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA