Cuente números enteros hasta N que se pueden representar como la suma de dos o más números consecutivos

Dado un entero positivo N , la tarea es contar el número de enteros hasta N que se pueden representar como la suma de dos o más números consecutivos .

Ejemplos: 

Entrada: N = 7
Salida: 4
Explicación: En el rango [1, 7]: {3, 5, 6, 7} se puede representar como suma de números consecutivos.

  • 3 = 1 + 2
  • 5 = 2 + 3
  • 6 = 1 + 2 + 3
  • 7 = 3 + 4

Entrada: N = 15
Salida: 11

Enfoque ingenuo: siga los pasos a continuación para resolver el problema:

  1. Itere sobre todos los enteros en el rango [1, N] y para cada entero, verifique si se puede representar como la suma de dos o más enteros consecutivos o no.
  2. Para comprobar si un número puede expresarse como la suma de dos o más números consecutivos o no, consulte este artículo.

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 check if the number N
// can be expressed as sum of 2 or
// more consecutive numbers or not
bool isPossible(int N)
{
    return ((N & (N - 1)) && N);
}
 
// Function to count integers in the range
// [1, N] that can be expressed as sum of
// 2 or more consecutive numbers
void countElements(int N)
{
    // Stores the required count
    int count = 0;
 
    for (int i = 1; i <= N; i++) {
 
        if (isPossible(i))
            count++;
    }
    cout << count;
}
// Driver Code
int main()
{
    int N = 15;
    countElements(N);
 
    return 0;
}

Java

// Java program of the above approach
import java.io.*;
class GFG
{
 
// Function to check if the number N
// can be expressed as sum of 2 or
// more consecutive numbers or not
static int isPossible(int N)
{
    return (((N & (N - 1)) & N));
}
 
// Function to count integers in the range
// [1, N] that can be expressed as sum of
// 2 or more consecutive numbers
static void countElements(int N)
{
   
    // Stores the required count
    int count = 0;
    for (int i = 1; i <= N; i++)
    {
        if (isPossible(i) != 0)
            count++;
    }
    System.out.println(count);
}
 
// Driver Code
    public static void main(String[] args)
{
    int N = 15;
    countElements(N);
}
}
 
// This code is contributed by jana_sayantan.

Python3

# Python3 Program to implement
# the above approach
 
# Function to check if the number N
# can be expressed as sum of 2 or
# more consecutive numbers or not
def isPossible(N):
    return ((N & (N - 1)) and N)
 
# Function to count integers in the range
# [1, N] that can be expressed as sum of
# 2 or more consecutive numbers
def countElements(N):
   
    # Stores the required count
    count = 0
    for i in range(1, N + 1):
        if (isPossible(i)):
            count += 1
 
    print (count)
     
# Driver Code
if __name__ == '__main__':
    N = 15
    countElements(N)
 
    # This code is contributed by mohit kumar 29

C#

// C# program for the above approach
using System;
class GFG
{
 
// Function to check if the number N
// can be expressed as sum of 2 or
// more consecutive numbers or not
static int isPossible(int N)
{
    return (((N & (N - 1)) & N));
}
 
// Function to count integers in the range
// [1, N] that can be expressed as sum of
// 2 or more consecutive numbers
static void countElements(int N)
{
   
    // Stores the required count
    int count = 0;
    for (int i = 1; i <= N; i++)
    {
        if (isPossible(i) != 0)
            count++;
    }
    Console.Write(count);
}
 
// Driver Code
static public void Main()
{
    int N = 15;
    countElements(N);
}
}
 
// This code is contributed by code_hunt.

Javascript

<script>
 
// JavaScript program of the above approach
 
    // Function to check if the number N
    // can be expressed as sum of 2 or
    // more consecutive numbers or not
    function isPossible(N) {
        return (((N & (N - 1)) & N));
    }
 
    // Function to count integers in the range
    // [1, N] that can be expressed as sum of
    // 2 or more consecutive numbers
    function countElements(N) {
 
        // Stores the required count
        var count = 0;
        for (i = 1; i <= N; i++) {
            if (isPossible(i) != 0)
                count++;
        }
        document.write(count);
    }
 
    // Driver Code
     
        var N = 15;
        countElements(N);
 
// This code contributed by Rajput-Ji
 
</script>
Producción: 

11

 

Complejidad temporal: O(N)
Espacio auxiliar: O(1)

Enfoque eficiente: para optimizar el enfoque anterior, siga los pasos a continuación para resolver el problema 

  1. Todos los números, excepto los que son potencias de 2 , se pueden expresar como una suma de números consecutivos.
  2. Cuente el número de potencias de 2 ≤ N y guárdelo en una variable, k diga Count
  3. Escriba (N – Contar) como la respuesta requerida.

A continuación se muestra la implementación del enfoque anterior:

C++

// C++ implementation
// of the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to count integers in the range
// [1, N] that can be expressed as sum of
// 2 or more consecutive numbers
void countElements(int N)
{
    int Cur_Ele = 1;
    int Count = 0;
 
    // Count powers of 2 up to N
    while (Cur_Ele <= N) {
 
        // Increment count
        Count++;
 
        // Update current power of 2
        Cur_Ele = Cur_Ele * 2;
    }
 
    cout << N - Count;
}
 
// Driver Code
int main()
{
    int N = 15;
    countElements(N);
 
    return 0;
}

Java

// Java implementation
// of the above approach
import java.util.*;
class GFG
{
 
  // Function to count integers in the range
  // [1, N] that can be expressed as sum of
  // 2 or more consecutive numbers
  static void countElements(int N)
  {
    int Cur_Ele = 1;
    int Count = 0;
 
    // Count powers of 2 up to N
    while (Cur_Ele <= N)
    {
 
      // Increment count
      Count++;
 
      // Update current power of 2
      Cur_Ele = Cur_Ele * 2;
    }
 
    System.out.print(N - Count);
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    int N = 15;
    countElements(N);
  }
}
 
// This code is contributed by shikhasingrajput

Python3

# python 3 implementation
# of the above approach
 
# Function to count integers in the range
# [1, N] that can be expressed as sum of
# 2 or more consecutive numbers
def countElements(N):
    Cur_Ele = 1
    Count = 0
 
    # Count powers of 2 up to N
    while (Cur_Ele <= N):
        # Increment count
        Count += 1
 
        # Update current power of 2
        Cur_Ele = Cur_Ele * 2
 
    print(N - Count)
 
# Driver Code
if __name__ == '__main__':
    N = 15
    countElements(N)

C#

// C# implementation
// of the above approach
using System;
 
public class GFG
{
 
  // Function to count integers in the range
  // [1, N] that can be expressed as sum of
  // 2 or more consecutive numbers
  static void countElements(int N)
  {
    int Cur_Ele = 1;
    int Count = 0;
 
    // Count powers of 2 up to N
    while (Cur_Ele <= N)
    {
 
      // Increment count
      Count++;
 
      // Update current power of 2
      Cur_Ele = Cur_Ele * 2;
    }
 
    Console.Write(N - Count);
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
    int N = 15;
    countElements(N);
  }
}
 
// This code is contributed by 29AjayKumar

Javascript

<script>
 
// Javascript implementation
// of the above approach
 
// Function to count integers in the range
// [1, N] that can be expressed as sum of
// 2 or more consecutive numbers
function countElements(N)
{
    var Cur_Ele = 1;
    var Count = 0;
 
    // Count powers of 2 up to N
    while (Cur_Ele <= N)
    {
         
        // Increment count
        Count++;
 
        // Update current power of 2
        Cur_Ele = Cur_Ele * 2;
    }
    document.write(N - Count);
}
 
// Driver Code
var N = 15;
 
countElements(N);
 
// This code is contributed by todaysgaurav
 
</script>
Producción: 

11

 

Complejidad de tiempo: O(log(N))
Espacio auxiliar: O(1)

Publicación traducida automáticamente

Artículo escrito por shekabhi1208 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *