The Wayback Machine - https://web.archive.org/web/20240828110553/https://www.geeksforgeeks.org/program-for-armstrong-numbers/
Open In App

Program for Armstrong Numbers

Last Updated : 02 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Easy
49.88%
1.5L

Given a number x, determine whether the given number is Armstrong’s number or not.

A positive integer of n digits is called an Armstrong number of order n (order is the number of digits) if

abcd... = pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n) + .... 

Example: 

Input:153
Output: Yes
153 is an Armstrong number.
1*1*1 + 5*5*5 + 3*3*3 = 153

Input: 120
Output: No
120 is not a Armstrong number.
1*1*1 + 2*2*2 + 0*0*0 = 9

Input: 1253
Output: No
1253 is not a Armstrong Number
1*1*1*1 + 2*2*2*2 + 5*5*5*5 + 3*3*3*3 = 723

Input: 1634
Output: Yes
1*1*1*1 + 6*6*6*6 + 3*3*3*3 + 4*4*4*4 = 1634

Naive Approach

The idea is to first count the number of digits (or find the order). 

Algorithm:

  1. Let the number of digits be n. 
  2. For every digit r in input number x, compute rn. 
  3. If the sum of all such values is equal to x, then return true, else false. 

Below is the program to check whether the number is an Armstrong number or not:

C++
// C++ program to determine whether 
// the number is Armstrong number or not
#include <bits/stdc++.h>
using namespace std;

// Function to calculate x raised 
// to the power y 
int power(int x, unsigned int y)
{
    if (y == 0)
        return 1;
    if (y % 2 == 0)
        return power(x, y / 2) * power(x, y / 2);
    return x * power(x, y / 2) * power(x, y / 2);
}

/* Function to calculate order of the number */
int order(int x)
{
    int n = 0;
    while (x) {
        n++;
        x = x / 10;
    }
    return n;
}

// Function to check whether the given 
// number is Armstrong number or not
bool isArmstrong(int x)
{
    // Calling order function
    int n = order(x);
    int temp = x, sum = 0;
    while (temp) {
        int r = temp % 10;
        sum += power(r, n);
        temp = temp / 10;
    }

    // If satisfies Armstrong condition
    return (sum == x);
}

// Driver Code
int main()
{
    int x = 153;
    cout << boolalpha << isArmstrong(x) << endl;
    x = 1253;
    cout << boolalpha << isArmstrong(x) << endl;
    return 0;
}
C
// C program to find Armstrong number
#include <stdio.h>

// Function to calculate x raised to 
// the power y 
int power(int x, unsigned int y)
{
    if (y == 0)
        return 1;
    if (y % 2 == 0)
        return power(x, y / 2) * power(x, y / 2);
    return x * power(x, y / 2) * power(x, y / 2);
}

// Function to calculate order of the number 
int order(int x)
{
    int n = 0;
    while (x) {
        n++;
        x = x / 10;
    }
    return n;
}

// Function to check whether the 
// given number is Armstrong number or not
int isArmstrong(int x)
{
    // Calling order function
    int n = order(x);
    int temp = x, sum = 0;
    while (temp) {
        int r = temp % 10;
        sum += power(r, n);
        temp = temp / 10;
    }

    // If satisfies Armstrong condition
    if (sum == x)
        return 1;
    else
        return 0;
}

// Driver Code
int main()
{
    int x = 153;
    if (isArmstrong(x) == 1)
        printf("True\n");
    else
        printf("False\n");

    x = 1253;
    if (isArmstrong(x) == 1)
        printf("True\n");
    else
        printf("False\n");

    return 0;
}
Java
// Java program to determine whether 
// the number is Armstrong number or not
public class Armstrong {
    
    // Function to calculate x raised 
    // to the power y 
    int power(int x, long y)
    {
        if (y == 0)
            return 1;
        if (y % 2 == 0)
            return power(x, y / 2) * power(x, y / 2);
        return x * power(x, y / 2) * power(x, y / 2);
    }

    // Function to calculate order of the number 
    int order(int x)
    {
        int n = 0;
        while (x != 0) {
            n++;
            x = x / 10;
        }
        return n;
    }

    // Function to check whether the given 
    // number is Armstrong number or not
    boolean isArmstrong(int x)
    {
        // Calling order function
        int n = order(x);
        int temp = x, sum = 0;
        while (temp != 0) {
            int r = temp % 10;
            sum = sum + power(r, n);
            temp = temp / 10;
        }

        // If satisfies Armstrong condition
        return (sum == x);
    }

    // Driver Code
    public static void main(String[] args)
    {
        Armstrong ob = new Armstrong();
        int x = 153;
        System.out.println(ob.isArmstrong(x));
        x = 1253;
        System.out.println(ob.isArmstrong(x));
    }
}
Python
# Python program to determine whether the number is
# Armstrong number or not

# Function to calculate x raised to the power y


def power(x, y):
    if y == 0:
        return 1
    if y % 2 == 0:
        return power(x, y/2)*power(x, y/2)
    return x*power(x, y/2)*power(x, y/2)

# Function to calculate order of the number


def order(x):

    # variable to store of the number
    n = 0
    while (x != 0):
        n = n+1
        x = x/10
    return n

# Function to check whether the given number is
# Armstrong number or not


def isArmstrong(x):
    n = order(x)
    temp = x
    sum1 = 0
    while (temp != 0):
        r = temp % 10
        sum1 = sum1 + power(r, n)
        temp = temp/10

    # If condition satisfies
    return (sum1 == x)


# Driver Program
x = 153
print(isArmstrong(x))
x = 1253
print(isArmstrong(x))
Python3
# python3 >= 3.6 for typehint support
# This example avoids the complexity of ordering
# through type conversions & string manipulation


def isArmstrong(val: int) -> bool:
    """val will be tested to see if its an Armstrong number. 
    Arguments:
        val {int} -- positive integer only. 
    Returns:
        bool -- true is /false isn't
    """

    # break the int into its respective digits
    parts = [int(_) for _ in str(val)]

    # begin test.
    counter = 0
    for _ in parts:
        counter += _**3
    return (counter == val)


# Check Armstrong number
print(isArmstrong(153))

print(isArmstrong(1253))
C#
// C# program to determine whether the
// number is Armstrong number or not
using System;

public class GFG {

    // Function to calculate x raised
    // to the power y
    int power(int x, long y)
    {
        if (y == 0)
            return 1;
        if (y % 2 == 0)
            return power(x, y / 2) * power(x, y / 2);

        return x * power(x, y / 2) * power(x, y / 2);
    }

    // Function to calculate
    // order of the number
    int order(int x)
    {
        int n = 0;
        while (x != 0) {
            n++;
            x = x / 10;
        }
        return n;
    }

    // Function to check whether the
    // given number is Armstrong number
    // or not
    bool isArmstrong(int x)
    {

        // Calling order function
        int n = order(x);
        int temp = x, sum = 0;
        while (temp != 0) {
            int r = temp % 10;
            sum = sum + power(r, n);
            temp = temp / 10;
        }

        // If satisfies Armstrong condition
        return (sum == x);
    }

    // Driver Code
    public static void Main()
    {
        GFG ob = new GFG();
        int x = 153;
        Console.WriteLine(ob.isArmstrong(x));
        x = 1253;
        Console.WriteLine(ob.isArmstrong(x));
    }
}

// This code is contributed by Nitin Mittal.
JavaScript
<script>

    // JavaScript program to determine whether the 
    // number is Armstrong number or not
    
    // Function to calculate x raised
    // to the power y
    function power(x, y)
    {
        if( y == 0)
            return 1;
        if (y % 2 == 0)
            return power(x, parseInt(y / 2, 10)) * 
                   power(x, parseInt(y / 2, 10));
                     
        return x * power(x, parseInt(y / 2, 10)) *
                   power(x, parseInt(y / 2, 10));
    }
  
    // Function to calculate 
    // order of the number
    function order(x)
    {
        let n = 0;
        while (x != 0)
        {
            n++;
            x = parseInt(x / 10, 10);
        }
        return n;
    }
  
    // Function to check whether the 
    // given number is Armstrong number
    // or not
    function isArmstrong(x)
    {
          
        // Calling order function
        let n = order(x);
        let temp = x, sum = 0;
        while (temp != 0)
        {
            let r = temp % 10;
            sum = sum + power(r, n);
            temp = parseInt(temp / 10, 10);
        }
  
        // If satisfies Armstrong condition
        return (sum == x);
    }
    
    let x = 153;
    if(isArmstrong(x))
    {
        document.write("True" + "</br>");
    }
    else{
        document.write("False" + "</br>");
    }
    x = 1253;
    if(isArmstrong(x))
    {
        document.write("True");
    }
    else{
        document.write("False");
    }

</script>

Output
true
false

Find nth Armstrong Number 

Input: 9
Output: 9

Input: 10
Output: 153

Below is the program to find the nth Armstrong number:

C++
// C++ Program to find
// Nth Armstrong Number
#include <bits/stdc++.h>
#include <math.h>
using namespace std;

// Function to find Nth Armstrong Number
int NthArmstrong(int n)
{
    int count = 0;

    // upper limit from integer
    for (int i = 1; i <= INT_MAX; i++) {
        int num = i, rem, digit = 0, sum = 0;

        // Copy the value for num in num
        num = i;

        // Find total digits in num
        digit = (int)log10(num) + 1;

        // Calculate sum of power of digits
        while (num > 0) {
            rem = num % 10;
            sum = sum + pow(rem, digit);
            num = num / 10;
        }
        // Check for Armstrong number
        if (i == sum)
            count++;
        if (count == n)
            return i;
    }
}

// Driver Code
int main()
{
    int n = 12;
    cout << NthArmstrong(n);
    return 0;
}

// This Code is Contributed by 'jaingyayak'
C
// C Program to find
// Nth Armstrong Number
#include <limits.h>
#include <math.h>
#include <stdio.h>

// Function to find Nth Armstrong Number
int NthArmstrong(int n)
{
    int count = 0;

    // upper limit from integer
    for (int i = 1; i <= INT_MAX; i++) {
        int num = i, rem, digit = 0, sum = 0;

        // Copy the value for num in num
        num = i;

        // Find total digits in num
        digit = (int)log10(num) + 1;

        // Calculate sum of power of digits
        while (num > 0) {
            rem = num % 10;
            sum = sum + pow(rem, digit);
            num = num / 10;
        }
        // Check for Armstrong number
        if (i == sum)
            count++;
        if (count == n)
            return i;
    }
}

// Driver Code
int main()
{
    int n = 12;
    printf("%d", NthArmstrong(n));
    return 0;
}

// This Code is Contributed by 'sathiyamoorthics19'
Java
// Java Program to find
// Nth Armstrong Number
import java.lang.Math;

class GFG {

    // Function to find Nth Armstrong Number
    static int NthArmstrong(int n)
    {
        int count = 0;

        // upper limit from integer
        for (int i = 1; i <= Integer.MAX_VALUE; i++) {
            int num = i, rem, digit = 0, sum = 0;

            // Copy the value for num in num
            num = i;

            // Find total digits in num
            digit = (int)Math.log10(num) + 1;

            // Calculate sum of power of digits
            while (num > 0) {
                rem = num % 10;
                sum = sum + (int)Math.pow(rem, digit);
                num = num / 10;
            }

            // Check for Armstrong number
            if (i == sum)
                count++;
            if (count == n)
                return i;
        }
        return n;
    }

    // Driver Code
    public static void main(String[] args)
    {
        int n = 12;
        System.out.println(NthArmstrong(n));
    }
}

// This code is contributed by Code_Mech.
Python
# Python3 Program to find Nth Armstrong Number
import math
import sys

# Function to find Nth Armstrong Number


def NthArmstrong(n):

    count = 0

    # upper limit from integer
    for i in range(1, sys.maxsize):

        num = i
        rem = 0
        digit = 0
        sum = 0

        # Copy the value for num in num
        num = i

        # Find total digits in num
        digit = int(math.log10(num) + 1)

        # Calculate sum of power of digits
        while(num > 0):
            rem = num % 10
            sum = sum + pow(rem, digit)
            num = num // 10

        # Check for Armstrong number
        if(i == sum):
            count += 1
        if(count == n):
            return i


# Driver Code
n = 12
print(NthArmstrong(n))

# This code is contributed by chandan_jnu
C#
// C# Program to find
// Nth Armstrong Number
using System;

class GFG {

    // Function to find Nth Armstrong Number
    static int NthArmstrong(int n)
    {
        int count = 0;

        // upper limit from integer
        for (int i = 1; i <= int.MaxValue; i++) {
            int num = i, rem, digit = 0, sum = 0;

            // Copy the value for num in num
            num = i;

            // Find total digits in num
            digit = (int)Math.Log10(num) + 1;

            // Calculate sum of power of digits
            while (num > 0) {
                rem = num % 10;
                sum = sum + (int)Math.Pow(rem, digit);
                num = num / 10;
            }

            // Check for Armstrong number
            if (i == sum)
                count++;
            if (count == n)
                return i;
        }
        return n;
    }

    // Driver Code
    public static void Main()
    {
        int n = 12;
        Console.WriteLine(NthArmstrong(n));
    }
}

// This code is contributed by Code_Mech.
JavaScript
<script>

// Javascript program to find Nth Armstrong Number

// Function to find Nth Armstrong Number
function NthArmstrong(n)
{
    let count = 0;

    // Upper limit from integer
    for(let i = 1; i <= Number.MAX_VALUE; i++)
    {
        let num = i, rem, digit = 0, sum = 0;

        // Copy the value for num in num
        num = i;

        // Find total digits in num
        digit = parseInt(Math.log10(num), 10) + 1;

        // Calculate sum of power of digits
        while(num > 0)
        {
            rem = num % 10;
            sum = sum + Math.pow(rem, digit);
            num = parseInt(num / 10, 10);
        }

        // Check for Armstrong number
        if (i == sum)
            count++;
        if (count == n)
            return i;
    }
    return n;
}

// Driver code
let n = 12;

document.write(NthArmstrong(n));

// This code is contributed by rameshtravel07   

</script>
PHP
<?php
// PHP Program to find 
// Nth Armstrong Number

// Function to find
// Nth Armstrong Number
function NthArmstrong($n)
{
    $count = 0;
    
    // upper limit
    // from integer 
    for($i = 1; 
        $i <= PHP_INT_MAX; $i++)
    {
        $num = $i; 
        $rem;
        $digit = 0;
        $sum = 0;
        
        // Copy the value 
        // for num in num 
        $num = $i;
        
        // Find total 
        // digits in num 
        $digit = (int) log10($num) + 1;
        
        // Calculate sum of
        // power of digits 
        while($num > 0)
        { 
            $rem = $num % 10;
            $sum = $sum + pow($rem, 
                              $digit);
            $num = (int)$num / 10;
        }
        
        // Check for 
        // Armstrong number 
        if($i == $sum)
            $count++;
        if($count == $n)
            return $i;
    }
}

// Driver Code
$n = 12;
echo NthArmstrong($n);

// This Code is Contributed 
// by akt_mit
?>

Output
371

Time complexity: O(log n)
Auxiliary Space: O(1)

Using Numeric Strings

When considering the number as a string we can access any digit we want and perform operations. Below is the program to implement the above approach:

C++
// C++ program to check whether the
// number is Armstrong number or not
#include <bits/stdc++.h>

using namespace std;

string armstrong(int n)
{
    string number = to_string(n);

    n = number.length();
    long long output = 0;
    for (char i : number)
        output = output + (long)pow((i - '0'), n);

    if (output == stoll(number))
        return ("True");
    else
        return ("False");
}

// Driver Code
int main()
{
    cout << armstrong(153) << endl;
    cout << armstrong(1253) << endl;
}

// This code is contributed by phasing17
Java
// Java program to check whether the
// number is Armstrong number or not
public class armstrongNumber {
    public void isArmstrong(String n)
    {
        char[] s = n.toCharArray();
        int size = s.length;
        int sum = 0;

        for (char num : s) {
            int temp = 1;
            int i
                = Integer.parseInt(Character.toString(num));

            for (int j = 0; j <= size - 1; j++) {
                temp *= i;
            }
            sum += temp;
        }

        if (sum == Integer.parseInt(n)) {
            System.out.println("True");
        }
        else {
            System.out.println("False");
        }
    }

    // Driver Code
    public static void main(String[] args)
    {
        armstrongNumber am = new armstrongNumber();
        am.isArmstrong("153");
        am.isArmstrong("1253");
    }
}
Python
def armstrong(n):
    number = str(n)

    n = len(number)
    output = 0
    for i in number:
        output = output+int(i)**n

    if output == int(number):
        return(True)
    else:
        return(False)


print(armstrong(153))
print(armstrong(1253))
C#
using System;
public class armstrongNumber {
    public void isArmstrong(String n)
    {
        char[] s = n.ToCharArray();
        int size = s.Length;
        int sum = 0;
        foreach(char num in s)
        {
            int temp = 1;
            int i = Int32.Parse(char.ToString(num));
            for (int j = 0; j <= size - 1; j++) {
                temp *= i;
            }
            sum += temp;
        }
        if (sum == Int32.Parse(n)) {
            Console.WriteLine("True");
        }
        else {
            Console.WriteLine("False");
        }
    }

    public static void Main(String[] args)
    {
        armstrongNumber am = new armstrongNumber();
        am.isArmstrong("153");
        am.isArmstrong("1253");
    }
}

// This code is contributed by umadevi9616
JavaScript
<script>
function armstrong(n){
    let number = new String(n)

    n = number.length
    let output = 0
    for(let i of number)
      output = output + parseInt(i)**n

    if (output == parseInt(number))
        return("True" + "<br>")
    else
        return("False" + "<br>")
}
        
document.write(armstrong(153))
document.write(armstrong(1253))

// This code is contributed by _saurabh_jaiswal.
</script>

Output
True
False


Time Complexity: O(n).
Auxiliary Space: O(1).

Find all Armstrong Numbers in a Range

Below is the program to find all Armstrong numbers in a given range:

C++
// C++ program to find all Armstrong numbers
// in a given range
#include <bits/stdc++.h>
using namespace std;

void isArmstrong(int left, int right)
{
    for (int i = left; i <= right; i++) {
        int sum = 0;
        int temp = i;
        while (temp > 0) {
            // Finding the lastdigit
            int lastdigit = temp % 10;

            // Finding the sum
            sum += pow(lastdigit, 3);
            temp /= 10;
        }

        // Condition to print the number if
        // it is armstrong number
        if (sum == i) {
            cout << i << " ";
        }
    }
    cout << endl;
}

// Driver code
int main()
{
    int left = 5, right = 1000;
    isArmstrong(left, right);
    return 0;
}

// This code is contributed by 525tamannacse11
Java
// Java program to find all Armstrong numbers
// in a given range

// Importing necessary libraries
import java.util.*;

public class Main {
    public static void isArmstrong(int left, int right)
    {
        for (int i = left; i <= right; i++) {
            int sum = 0;
            int temp = i;
            while (temp > 0) {
                // Finding the last digit
                int lastdigit = temp % 10;

                // Finding the sum
                sum += Math.pow(lastdigit, 3);
                temp /= 10;
            }

            // Condition to print the number if it
            // is an Armstrong number
            if (sum == i) {
                System.out.print(i + " ");
            }
        }
        System.out.println();
    }

    // Driver code
    public static void main(String[] args)
    {
        int left = 5, right = 1000;
        isArmstrong(left, right);
    }
}
Python
def armstrong(n):
    number = str(n)

    n = len(number)
    output = 0
    for i in number:
        output = output+int(i)**n

    if output == int(number):
        return(True)
    else:
        return(False)


arm_list = []

nums = range(10, 1000)

for i in nums:
    if armstrong(i):
        arm_list.append(i)
    else:
        pass

print(arm_list)
C#
using System;

class MainClass {
    static void isArmstrong(int left, int right)
    {
        for (int i = left; i <= right; i++) {
            int sum = 0;
            int temp = i;
            while (temp > 0) {
                // finding the lastdigit
                int lastdigit = temp % 10;
                // finding the sum
                sum += (int)Math.Pow(lastdigit, 3);
                temp /= 10;
            }
            /* Condition to print the number if it is
             * armstrong number */
            if (sum == i) {
                Console.Write(i + " ");
            }
        }
        Console.WriteLine();
    }

    public static void Main(string[] args)
    {
        int left = 5, right = 1000;
        isArmstrong(left, right);
    }
}
JavaScript
// JavaScript code to implement the approach
function isArmstrong(left, right) {
    for (let i = left; i <= right; i++) {
        let sum = 0;
        let temp = i;
        while (temp > 0) {
            // finding the lastdigit
            let lastdigit = temp % 10;
            // finding the sum
            sum += Math.pow(lastdigit, 3);
            temp = Math.floor(temp / 10);
        }
        /* Condition to print the number if it is armstrong number */
        if (sum === i) {
            process.stdout.write(i + " ");
        }
    }
    console.log("\n");
}

// Driver code

let left = 5,
    right = 1000;
isArmstrong(left, right);

// This code is contributed by phasing17

Output
153 370 371 407 


References: 
http://www.cs.mtu.edu/~shene/COURSES/cs201/NOTES/chap04/arms.html 
http://www.programiz.com/c-programming/examples/check-armstrong-number

This article is contributed by Rahul Agrawal .



Similar Reads

XOR and OR of all N-digit Armstrong numbers
Given an integer N, the task is to find the XOR and OR values of all N-digit Armstrong numbers. Examples Input: N = 3 Output: XOR = 271, OR = 511 153, 370, 371, 407 are the three digit armstrong numbers Input: N = 4 Output: XOR = 880, OR = 10098 Approach: Find the starting and ending number of N-digit Armstrong number by:Starting N-digit Armstrong
7 min read
Sum of all armstrong numbers lying in the range [L, R] for Q queries
Given Q queries in the form of a 2D array arr[][] in which every row consists of two numbers L and R which denotes a range [L, R], the task is to find the sum of all Armstrong Numbers lying in the given range [L, R].Examples: Input: Q = 2, arr = [ [1, 13], [121, 211] ] Output: 45 153 Explanation: From 1 to 13, 1, 2, 3, 4, 5, 6, 7, 8 and 9 are the A
9 min read
Range Queries for number of Armstrong numbers in an array with updates
Given an array arr[] of N integers, the task is to perform the following two queries: query(start, end): Print the number of Armstrong numbers in the subarray from start to endupdate(i, x): Add x to the array element referenced by array index i, that is: arr[i] = x Examples: Input: arr = { 18, 153, 8, 9, 14, 5} Query 1: query(start = 0, end = 4) Qu
15+ min read
Range Queries for count of Armstrong numbers in subarray using MO's algorithm
Given an array arr[] consisting of N elements and Q queries represented by L and R denoting a range, the task is to print the number of Armstrong numbers in the subarray [L, R]. Examples: Input: arr[] = {18, 153, 8, 9, 14, 5} Query 1: query(L=0, R=5) Query 2: query(L=3, R=5) Output: 4 2 Explanation: 18 =&gt; 1*1 + 8*8 != 18 153 =&gt; 1*1*1 + 5*5*5
15 min read
Maximum number of Armstrong Numbers present in a subarray of size K
Given an array arr[] consisting of N integers and a positive integer K, the task is to find the maximum count of Armstrong Numbers present in any subarray of size K. Examples: Input: arr[] = {28, 2, 3, 6, 153, 99, 828, 24}, K = 6Output: 4Explanation: The subarray {2, 3, 6, 153} contains only of Armstrong Numbers. Therefore, the count is 4, which is
12 min read
Find GCD of largest and smallest Armstrong numbers in a given range
Given a range of positive integers, find the Greatest Common Divisor (GCD) of the largest and smallest Armstrong numbers within that range. Examples: Input: Range [100, 10000]Output: 3Explanation: Smallest Armstrong number in the given range is 153, and the largest Armstrong number in the given range is 9474. The GCD of 153 and 9474 is 3. Input: Ra
6 min read
Armstrong Numbers between two integers
A positive integer with digits a, b, c, d... is called an Armstrong number of order n if following condition is satisfied. abcd... = an + bn + cn + dn +... 153 = 1*1*1 + 5*5*5 + 3*3*3 = 1 + 125 + 27 = 153 Therefore, 153 is an Armstrong number. Examples: Input : 100 400 Output :153 370 371 Explanation : 100 and 400 are given two integers.(interval)
6 min read
Check if a Linked List is an Armstrong Number
Given a singly linked list List containing N nodes representing a number, the task is to check whether the given linked list is an Armstrong number. Print "1" if the given linked list is an Armstrong number, else print "0". Note: An Armstrong number is a number that is equal to the sum of its own digits each raised to the power of the number of dig
15 min read
Find largest Armstrong number in an Array
Given an array arr[] of size N. The task is to find the largest Armstrong number of the array. Note: An Armstrong number is a number that is equal to the sum of its digits raised to the power of the number of digits in that number. Examples: Input: arr[] = [153, 9474, 1634, 371, 8208, 9475]Output: 9474Explanation: The largest Armstrong number in th
7 min read
Array Range Queries to find the Maximum Armstrong number with updates
Given an array arr[] of N integers, the task is to perform the following two queries: maximum(start, end): Print the maximum Armstrong number of elements in the sub-array from start to endupdate(i, x): Add x to the array element referenced by array index i, that is: arr[i] = xIf there is no Armstrong number in the sub-array, print -1. Example: Inpu
15+ min read
Count strings having sum of ASCII values of characters equal to a Prime or Armstrong Number
Given an array arr[] of size N containing strings, the task is to count the number of strings having the sum of ASCII (American Standard Code for Information Interchange) values of characters equal to an Armstrong Number number or a Prime Number. Examples: Input: arr[] = {"hello", "nace"}Output:Number of Armstrong Strings are: 1Number of Prime Stri
12 min read
Print numbers such that no two consecutive numbers are co-prime and every three consecutive numbers are co-prime
Given an integer N, the task is to print N integers ? 109 such that no two consecutive of these integers are co-prime and every 3 consecutive are co-prime. Examples: Input: N = 3 Output: 6 15 10Input: N = 4 Output: 6 15 35 14 Approach: We can just multiply consecutive primes and for the last number just multiply the gcd(last, last-1) * 2. We do thi
15+ min read
Kth element in permutation of first N natural numbers having all even numbers placed before odd numbers in increasing order
Given two integers N and K, the task is to find the Kth element in the permutation of first N natural numbers arranged such that all the even numbers appear before the odd numbers in increasing order. Examples : Input: N = 10, K = 3 Output: 6Explanation:The required permutation is {2, 4, 6, 8, 10, 1, 3, 5, 7, 9}.The 3rd number in the permutation is
9 min read
Count of numbers of length N having prime numbers at odd indices and odd numbers at even indices
Given a number N, the task is to calculate the count of numbers of length N having prime numbers at odd indices and odd numbers at even indices. Example: Input : N = 1Output: 5Explanation : All valid numbers length 1 are 1, 3, 5, 7, 9, here we have only 1 odd index, therefore we have 5 valid numbers. Input: N = 2Output: 20 Explanation: There are 20
5 min read
Python3 Program to Rotate all odd numbers right and all even numbers left in an Array of 1 to N
Given a permutation arrays A[] consisting of N numbers in range [1, N], the task is to left rotate all the even numbers and right rotate all the odd numbers of the permutation and print the updated permutation. Note: N is always even.Examples:  Input: A = {1, 2, 3, 4, 5, 6, 7, 8} Output: {7, 4, 1, 6, 3, 8, 5, 2} Explanation: Even element = {2, 4, 6
2 min read
Javascript Program to Rotate all odd numbers right and all even numbers left in an Array of 1 to N
Given a permutation arrays A[] consisting of N numbers in range [1, N], the task is to left rotate all the even numbers and right rotate all the odd numbers of the permutation and print the updated permutation. Note: N is always even.Examples:  Input: A = {1, 2, 3, 4, 5, 6, 7, 8} Output: {7, 4, 1, 6, 3, 8, 5, 2} Explanation: Even element = {2, 4, 6
2 min read
Permutation of numbers such that sum of two consecutive numbers is a perfect square
Prerequisite: Hamiltonian Cycle Given an integer n(&gt;=2), find a permutation of numbers from 1 to n such that the sum of two consecutive numbers of that permutation is a perfect square. If that kind of permutation is not possible to print "No Solution". Examples: Input : 17 Output : [16, 9, 7, 2, 14, 11, 5, 4, 12, 13, 3, 6, 10, 15, 1, 8, 17] Expl
15+ min read
Numbers within a range that can be expressed as power of two numbers
Given two integers L and R. Find the number of perfect powers in the given range [L, R]. A number x is said to be perfect power if there exists some integers a &gt; 0, p &gt; 1 such that x = ap. Examples : Input : 1 4 Output : 2 Explanation : Suitable numbers are 1 and 4 where 1 can be expressed as 1 = 12 and 4 can be expressed as 4 = 22 Input : 12
12 min read
Print all distinct integers that can be formed by K numbers from a given array of N numbers
Given an array of N elements and an integer K, print all the distinct integers which can be formed by choosing K numbers from the given N numbers. A number from an array can be chosen any number of times. Examples: Input: k = 2, a[] = {3, 8, 17, 5} Output: The 10 distinct integers are: 6 8 10 11 13 16 20 22 25 34 The 2 elements chosen are: 3+3 = 6,
7 min read
Numbers less than N which are product of exactly two distinct prime numbers
Given a number [Tex]N [/Tex]. The task is to find all such numbers less than N and are a product of exactly two distinct prime numbers. For Example, 33 is the product of two distinct primes i.e 11 * 3, whereas numbers like 60 which has three distinct prime factors i.e 2 * 2 * 3 * 5.Note: These numbers cannot be a perfect square.Examples: Input : N
8 min read
Print N lines of 4 numbers such that every pair among 4 numbers has a GCD K
Given N and K, the task is to print N lines where each line contains 4 numbers such that every among those 4 numbers has a GCD K and the maximum number used in N*4 should be minimized.Note: In case of multiple outputs, print any one. Examples: Input: N = 1, K = 1 Output: 1 2 3 5 Every pair among 1, 2, 3 and 5 gives a GCD K and the largest number am
5 min read
Absolute Difference between the Sum of Non-Prime numbers and Prime numbers of an Array
Given an array of positive numbers, the task is to calculate the absolute difference between sum of non-prime numbers and prime numbers. Note: 1 is neither prime nor non-prime. Examples: Input : 1 3 5 10 15 7 Output : 10 Explanation: Sum of non-primes = 25 Sum of primes = 15 Input : 3 4 6 7 Output : 0 Naive Approach: A simple solution is to travers
15+ min read
Absolute difference between the Product of Non-Prime numbers and Prime numbers of an Array
Given an array of positive numbers, the task is to calculate the absolute difference between product of non-prime numbers and prime numbers.Note: 1 is neither prime nor non-prime.Examples: Input : arr[] = {1, 3, 5, 10, 15, 7} Output : 45 Explanation : Product of non-primes = 150 Product of primes = 105 Input : arr[] = {3, 4, 6, 7} Output : 3 Naive
15 min read
Count numbers which are divisible by all the numbers from 2 to 10
Given an integer N, the task is to find the count of numbers from 1 to N which are divisible by all the numbers from 2 to 10. Examples: Input: N = 3000 Output: 1 2520 is the only number below 3000 which is divisible by all the numbers from 2 to 10. Input: N = 2000 Output: 0 Approach: Let's factorize numbers from 2 to 10. 2 = 2 3 = 3 4 = 22 5 = 5 6
3 min read
Bitwise AND of the sum of prime numbers and the sum of composite numbers in an array
Given an array of positive numbers, the task is to find the bitwise AND of the sum of non-prime numbers and the sum of prime numbers. Note that 1 is neither prime nor composite.Examples: Input: arr[] = {1, 3, 5, 10, 15, 7} Output: 9 Sum of non-primes = 10 + 15 = 25 Sum of primes = 3 + 5 + 7 = 15 25 &amp; 15 = 9Input: arr[] = {3, 4, 6, 7} Output: 10
9 min read
Absolute difference between the XOR of Non-Prime numbers and Prime numbers of an Array
Given an array arr[] of N positive integers, the task is to calculate the absolute difference between XOR of non-prime numbers and prime numbers. Note that 1 is neither prime nor composite.Examples: Input: arr[] = {1, 3, 5, 10, 15, 7} Output: 4 Xor of non-primes = 10 ^ 15 = 5 Xor of primes = 3 ^ 5 ^ 7 = 1 |5 - 1| = 4Input: arr[] = {3, 4, 6, 7} Outp
8 min read
Fill the missing numbers in the array of N natural numbers such that arr[i] not equal to i
Given an unsorted array arr[] consisting of N natural numbers and the missing numbers as 0 such that arr[i] ? i, the task is to find and fill these missing numbers without changing the initial order. Please note that the array can contain numbers from 1 to N only once. Examples: Input: arr[] = {7, 4, 0, 3, 0, 5, 1} Output: 7 4 6 3 2 5 1 Explanation
9 min read
Find ratio of zeroes, positive numbers and negative numbers in the Array
Given an array a of integers of size N integers, the task is to find the ratio of positive numbers, negative numbers and zeros in the array up to four decimal places. Examples: Input: a[] = {2, -1, 5, 6, 0, -3} Output: 0.5000 0.3333 0.1667 There are 3 positive, 2 negative, and 1 zero. Their ratio would be positive: 3/6 = 0.5000, negative: 2/6 = 0.3
7 min read
Check if a given pair of Numbers are Betrothed numbers or not
Given two positive numbers N and M, the task is to check whether the given pairs of numbers (N, M) form a Betrothed Numbers or not. Examples: Input: N = 48, M = 75 Output: Yes Explanation: The proper divisors of 48 are 1, 2, 3, 4, 6, 8, 12, 16, 24 Sum of proper divisors of 48 is 75(sum1) The proper divisors of 75 are 1, 3, 5, 15, 25 Sum of proper d
7 min read
Number of ways to obtain each numbers in range [1, b+c] by adding any two numbers in range [a, b] and [b, c]
Given three integers a, b and c. You need to select one integer from the range [a, b] and one integer from the range [b, c] and add them. The task to calculate the number of ways to obtain the sum for all the numbers in the range [1, b+c]. Examples: Input: a = 1, b = 2, c = 2 Output: 0, 0, 1, 1 Explanation: The numbers to be obtained are [1, b+c] =
10 min read
Article Tags :
Practice Tags :