Summe aller i, sodass (2^i + 1) % 3 = 0, wobei i im Bereich [1, n] liegt
Bei einer gegebenen ganzen Zahl N besteht die Aufgabe darin, die Summe aller i von 1 bis N so zu berechnen, dass (2 i + 1) % 3 = 0 .
Beispiele:
Eingabe: N = 3
Ausgabe: 4
Für i = 1, 2 ist 1 + 1 = 3 durch 3 teilbar.
Für i = 2 ist 2 2 + 1 = 5, was nicht durch 3 teilbar ist.
Für i = 3 ist 2 3 + 1 = 9 ist durch 3 teilbar.
Also Summe = 1 + 3 = 4 (für i = 1, 3)
Eingabe: N = 13
Ausgabe: 49
Ansatz: Wenn wir genau hinsehen, wird i immer eine ungerade Zahl sein, also 1, 3, 5, 7, ….. . Wir verwenden die Formel für die Summe der ersten n ungeraden Zahlen, die n * n ist .
Unten ist die Implementierung des obigen Ansatzes:
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>
4
Zeitkomplexität: O(1)
Falls Sie an Live-Kursen mit Experten teilnehmen möchten , beziehen Sie sich bitte auf DSA Live-Kurse für Berufstätige und Competitive Programming Live for Students .