perl - Print Armstrong numbers between 1 to 10 million -


how write logic using for loop or while loop printing armstrong numbers?

someone kindly explain how print armstrong numbers between 1 1,00,00,000.

this algorithm followed

step 1 : initializing variable min,max,n,sum,r,t step 2 : $n = <>; step 3 : find base of $n step 4 : using loop          ( (n = min; n < max ; n++ ) step 5 : logic          n=t,sum =0,r=t%10,t=n/10, step 6 :          sum = sum + (n ^ base ); step 6 :          if ( sum == num ) print armstrong numbers else not. 

i tried code code this

#!/usr/bin/perl use strict; use warnings; use diagnostics;  $n; chomp($n);  $min = 1; $max = 10000000 $r; $sum; $t;  $base = length($n); print "base $base\n";  ($n = $min; $n <= $max; $n++) {   $t = $n;   $sum = 0;   while ($t != 0) {     $r = $t % 10;     $t = $t / 10;     {       $sum = $sum + ($base * $r);     }     if ($sum == $n) {       print "$n\n";     }   } } 

several things:

  • it's bad practice declare my until need it.
  • you must remember numbers strings, , can manipulated string functions split.
  • c-like loops discouraged in perl because they're hard read.
  • constants should ...well... constant.

here's attempt. use split split digits array of digits. lot easier dividing ten. can number of digits taking scalar value of @digits array.

i can loop through @digits, taking each 1 power of $power , adding sum. use map command loop, have used for loop too.

#! /usr/bin/env perl # use strict; use warnings; use feature qw(say);  use constant {     min             => 1,     max             => 1_000_000, };  $number ( (+min..+max) ) {     @digits = split //, $number;     $power = @digits;     $sum = 0;     map { $sum += $_**$power } @digits;     if ( $sum == $number ) {         "$number armstrong number";     } } 

and output:

1 armstrong number 2 armstrong number 3 armstrong number 4 armstrong number 5 armstrong number 6 armstrong number 7 armstrong number 8 armstrong number 9 armstrong number 153 armstrong number 370 armstrong number 371 armstrong number 407 armstrong number 1634 armstrong number 8208 armstrong number 9474 armstrong number 54748 armstrong number 92727 armstrong number 93084 armstrong number 548834 armstrong number 

took bit on 5 seconds run.

instead of map, have done loop:

for $digit ( @digits ) {     $sum = $sum + ( $digit ** $power); } 

Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -