how i add five digit number by using modulus. i am beginner. by using the example say 12345. reply me fast.
views:
81answers:
5
+1
A:
What language are you using? For C:
int number = 12345;
int sum = 0;
sum += number % 10;
sum += (number / 10) % 10;
sum += (number / 100) % 10;
sum += (number / 1000) % 10;
sum += number / 10000;
Delan Azabani
2010-09-18 10:46:44
a for loop would be nice... :)
Ido
2010-09-18 10:48:47
A:
are we really supposed to do your homework? AND its so trivial, if you do not know it, the homework is there so you learn how to do it.
Next step: do the inverse, implement atoi
allo
2010-09-18 11:14:16
+1
A:
Here are some exemples in Perl :
#!/usr/bin/perl -l
use strict;
use warnings;
my $in = 12345; #input number
my $m = 2; # modulus
# gives the sum of the modulus of each digit
my $r = eval join'+',map{$_%$m}split(//,$in);
print $r; # 3
# gives the modulus of the sum of each digit
my $r2 = (eval join'+',split(//,$in))%$m;
print $r2; # 1
# same as the second one but with regex
$in =~ s/(\d)(?=\d)/$1+/g;
print eval($in)%$m; # 1
M42
2010-09-18 12:04:13
A:
gets.to_i.to_s.chars.map(&:to_i).reduce(:+)
Note: works for an arbitrary number of digits, not just 5. Also, this doesn't use modulus. Why would you? Just split by digit and add them.
Jörg W Mittag
2010-09-18 12:40:39