Code for Armstrong numbers not working - c++

Alright please go easy. Just learning C++ and first also question here. I've written a program to list all Armstrong numbers below 1000. While I have read the Wikipedia article on narcissistic numbers, I'm only looking for 3-digit ones. Which means I only care for the sum of the cubes of the digits.
It works by executing a for loop for 1 to 1000, checking whether the indexing variable is armstrong or not using a user defined function and printing it if it is. The user defined function works simply by using a while loop to isolate digits and matching the sum of the cubes to the original number. If it is true, then returns 1 otherwise return 0.
The problem is, I'm getting abolutely no numbers in the output. Only the cout statement in void main() appears and the rest is blank. Tried to debug as much as I could. Complier is Turbo C++. Code-
#include<iostream.h>
#include<conio.h>
int chk_as(int);//check_armstrong
void main()
{
clrscr();
cout<<"All Armstrong numbers below 1000 are:\n";
for(int i=1;i<=1000;i++)
{
if (chk_as(i)==1)
cout<<i<<endl;
}
getch();
}
int chk_as (int n)
{
int dgt;
int sum=0,det=0;//determinant
while (n!=0)
{
dgt=n%10;
n=n/10;
sum+=(dgt*dgt*dgt);
}
if (sum==n)
{det=1;}
else
{det=0;}
return det;
}

The problem is that you are dynamically changing the value of n in your method, but you need its original value to check the result.
Add in a temporary variable, say, t.
int t = n;
while (t!=0)
{
dgt=t%10;
t=t/10;
sum+=(dgt*dgt*dgt);
}
if (sum==n)
// ... etc.

EDIT: Nevermind... this was wrong
while (n!=0)
{
dgt=n%10;
n=n/10;
sum+=(dgt*dgt*dgt);
}
This runs forever as n never reaches 0.

The problem is, that in the end of the loop
while (n!=0)
{
dgt=n%10;
n=n/10;
sum+=(dgt*dgt*dgt);
}
n is 0, so the condition if (sum==n) is never true.
Try something like :
int chk_as (int n)
{
int copy = n;
int dgt;
int sum=0,det=0;//determinant
while (copy!=0)
{
dgt=copy%10;
copy=copy/10;
sum+=(dgt*dgt*dgt);
}
if (sum==n)
{det=1;}
else
{det=0;}
return det;
}

I have given here the program for finding armstrong number of a three digits number.
The condition for armstrong number is,
Sum of the cubes of its digits must equal to the number itself.
For example, 407 is given as input.
4 * 4 * 4 + 0 * 0 * 0 + 7 * 7 * 7 = 407 is an armstrong number.
#include <stdio.h>
int main()
{
int i, a, b, c, d;
printf("List of Armstrong Numbers between (100 - 999):\n");
for(i = 100; i <= 999; i++)
{
a = i / 100;
b = (i - a * 100) / 10;
c = (i - a * 100 - b * 10);
d = a*a*a + b*b*b + c*c*c;
if(i == d)
{
printf("%d\n", i);
}
}
return 0;
}
List of Armstrong Numbers between (100 - 999):
153
370
371
407
Reference: http://www.softwareandfinance.com/Turbo_C/Find_Armstrong_Number.html

Related

Memory + dynamic programming or recursion

Problem is that i have 64 megabytes on solution,so i can use only 16,777,216 int numbers.
But for answer i must use 33,333,333 numbers,so some answers will not be considered.
Actually, problem is this.
By the way, i had my own code instead:
#include <iostream>
using namespace std;
int sq(int x) {
return (long long)(x*x) %(1000000);
}
int func(int x) {
if (x==0)
return 3;
else {
return ( sq(func(x-1))+2)%(1000000);
}
}
int main()
{
/*const int num=16 777 216;
int* arr=new int [num];
arr[0]=3;
for (int i=1;i<num;i++)
arr[i]=((arr[i-1]%(1000000))*(arr[i-1])%(1000000)+2)%(1000000);*/
int t,rez;
int n;
cin>>t;
for (int p=0;p<t;p++) {
cin>>n;
if (n%3!=0) {
rez=0;
} else {
// rez=arr[n/3-1];
rez=func(n/3-1);
}
cout<<rez<<endl;
}
return 0;
}
In comments there is second solution.
I can do it with recursion, but i have limit in 1 second.
So what code would be OK?
You do not need anywhere near that many entries (10^9 / 3). Note that you need only the values mod 10^6. You have a recurrence relationship among these:
a[n] = a[n-1]^2 + 2
Each value depends only on the previous one, so there will be a simple sequence of numbers. The relation will have a period of no more than 10^6. Since they're all odd, the maximum length is cut in half.
As it turns out, the sequence repeats after 5003 terms, with a period of 5000: 3, 11, 123 do not appear later in the sequence.
So, forget that huge array. Compute the 5003 terms you need. Now for any input number N, you have 3 cases:
(1) N is not divisible by 3: return 0
else N is divisible by 3; call the quotient M
(2) M <= 3: return arr[M]
(3) else, get the needed subscript as m = ((M-3) mod 5000) + 3;
return arr[m]
You can now handle arbitrarily large input.

Why is only one Armstrong number being printed?

This is my assignment:
An Armstrong number of three digits is an integer such that the sum of
the cubes of its digits is equal to the number itself. For example,
153 is an Armstrong number since 1^3 + 5^3 + 3^3 = 153. Write a
function named is_armstrong that takes one positive integer number as
argument and returns a boolean variable which is true if the number is
an Armstrong number and return false otherwise. Use this function
is_armstrong in your main( ) function to print all Armstrong number in
the range of 100 and 999
I have written a program, but it only prints out one number, 999. Can anyone point out my error? Many thanks.
#include <iostream>
using namespace std;
//Function name: getRaiseAndAdd
//Purpose: Calculate each digit cubed and the sum of the results.
//We are sending in the current number from the loop starting at 100 and
//counting one by one to 999.
//Parameters: &numberInput
//Return value: Result of adding 3 numbers
int getRaiseAndAdd(int &numberInput)
{
int firstNumber, secondNumber, thirdNumber;
int remainder;
int sum;
int firstPower, secondPower, thirdPower;
firstNumber = numberInput / 100;
remainder = numberInput % 100;
secondNumber = remainder / 10;
thirdNumber = remainder % 10;
firstPower = firstNumber * firstNumber * firstNumber;
secondPower = secondNumber *secondNumber * secondNumber;
thirdPower = thirdNumber * thirdNumber * thirdNumber;
return sum = firstPower + secondPower + thirdPower;
}
int main()
{
int answer;
int originalNumber;
for(int i = 100; i < 1000; i++)
{
originalNumber = i;
answer = getRaiseAndAdd(i);
}
{
//Function name: is_Armstrong
//Purpose: finding the Armstrong numbers
//Parameters: answer
//Return value: 0
bool is_Armstrong (int answer);
if(answer == originalNumber);
{
cout<<"found an Armstrong number "<<originalNumber<<endl;
}
}
return 0;
}
There are a few things wrong with your code (your armstrong function seems fine though). First, your code to check if the number is an armstrong number is done after you loop through everything. This needs to be done inside the loop so that every number is checked.
Second, you have a semicolon after your if (if (answer == originalNumber); {...}). This causes execution to fall into the next block unconditionally, which is why it prints out 999 (which is not an armstrong number by the way).
So the fixes are to move your check into the loop and remove the semicolon after the if.
First you are running this loop:
for(int i = 100; i < 1000; i++)
{
originalNumber = i;
answer = getRaiseAndAdd(i);
}
after this originalNumber will be 999 and answer will be 999, too.
Only later you are running this check:
if(answer == originalNumber);
{
cout<<"found an Armstrong number "<<originalNumber<<endl;
}
}
You should make the check a proper function, you have a forward declaration, followed by a block, and call it from within the loop.
Starting from beginning of the main method to the end, you are printing one time. If you repeat your printing in a loop you will get multiple prints.
As Kevin stated:
putting the Check within the loop would solve your problem
for(int i = 100; i < 1000; i++)
{
originalNumber = i;
answer = getRaiseAndAdd(i);
if(answer == originalNumber)
{
cout<<"found an Armstrong number "<<originalNumber<<endl;
}
}
Ran it and got the result

How to make sum in a single digit?

I'm making a program to sum a digits, Have a look into this program:
#include<iostream>
using namespace std;
int main(){
int i, j;
int sum=1;
cout<<"Enter your sum: "<<endl;
cin>>i;
while(i>0){
j=i%10;
sum=sum+j;
i=i/10;
}
cout<<"Sum: "<<sum;
cout<<endl;
}
So, as I type into output as 25 it'll give me as an output 7.
But I want to make it in a single digit of every sum, let's say as I type 147. It gives me an output 10 but I want 1 as an output.
I know it could be done as:
while(i>0){
j=i%10;
sum=sum+j;
i=i/10;
}
cout<<"Sum: "<<sum/10;
and surely it'll give me an output as 1.
But as I type a number 185 it gives me an output 1.. But I want the whole sum of digit.
I want that program into which if i type 185
Output must suppose to be as
1+8+5=14
1+4=5
And output must be 5.. So please help me to resolve this kind of issue.
What you describe is called a digital root. Interestingly enough, it can be computed by simply determining the remainder when dividing by 9 - whereas 0 is substituted by 9.
unsigned digitalRoot(unsigned i)
{
return 1 + (i-1)%9; // if i%9==0, (i-1)%9==8 and adding 1 yields 9
}
digitalRoot(185) is 5 since 185 = 9*20 + 5.
as I type into output as 25 it'll give me as an output 7.
No, it is actually 8 (demo). The problem is that you initialize sum to 1 instead of 0.
As far as making the sum a single digit goes, add another loop to your program:
for (;;) { // Loop until the break is reached
while(i>0){
j=i%10;
sum=sum+j;
i=i/10;
}
if (sum < 10) break; // It's single digit
i = sum;
sum = 0;
}
You can try this:
while(i>0){
j=i%10;
sum=sum+j;
i=i/10;
if (i == 0 && sum >= 10) // if all the digits of previous number is processed and sum is not a single digit
{
i = sum;
sum = 0;
}
}
Note that there is no nested loop!
Do not forget to initialize sum to 0 instead of 1.
import java.util.*;
public class SingleDigit
{
public static void main(String[] args)
{
int number = 0, temp = 0, result = 0;
Scanner inp = new Scanner(System.in);
System.out.print("Enter the Number :");
number = inp.nextInt();
temp = number;
while(temp>0)
{
result = result + (temp%10);
temp = temp/10;
if(result > 9)
result = (result % 10)+(result / 10);
}
System.out.println("Single Digit Number for the Number "+number+" is :" result);
System.out.println("Thank You KING....");
}
}

run time error - non zero exception

my programming teacher gave me this problem to code it in c :
given array of N integers A and a number K. During a turn the maximal value over all Ai is chosen, let's call it MAX. Then Ai =
MAX - Ai is done for every 1 <= i <= N. Help Roman to find out how will the array look like after K turns.
Input
The numbers N and K are given in the first line of an input. Then N integers are given in the second line which denote the array A.
Output
Output N numbers on a single line. It should be the array A after K turns.
Constraints
* 1 <= N <= 10^5
* 0 <= K <= 10^9
* Ai does not exceed 2 * 10^9 by it's absolute value.
Example
Input:
4 1
5 -1 7 0
Output:
2 8 0 7
and my code to this problem is :
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
long int Max(long int *arr, int low, int high)
{
long int max,i;
max = arr[low];
for(i=0;i<=high;i++)
{
if(max<=arr[i])
max = arr[i];
}
return max;
}
/* Driver program to test above function */
int main()
{
long int max,*arr;
long int n,k,c1,c2,c3,i,j;
c1 = (long int)pow(10,5);
c2 = (long int)pow(10,9);
c3 = 2*c2;
scanf("%ld %ld",&n,&k);
if(n<1||n>c1)
exit(1);
else if(k<0||k>c2)
exit(1);
else
{
arr = (long int *)malloc(sizeof(int)*n);
for(i=0;i<n;i++)
{
scanf("%ld",&arr[i]);
if(abs(arr[i])>c3)
exit(1);
}
if(k%2 == 0)
{
for(i=0;i<2;i++)
{
max = Max(arr, 0, n-1);
for(j=0;j<n;j++)
{
arr[j] = max-arr[j];
if(abs(arr[j])>c3)
exit(1);
}
}
}
else if(k%2 != 0)
{
max = Max(arr, 0, n-1);
for(j=0;j<n;j++)
{
arr[j] = max-arr[j];
/*if(abs(arr[j])>c3)
exit(1);*/
}
}
/* for(m=0;m<n;m++)
printf("%ld ",arr[m]);
printf("\n");*/
for(i=0;i<n;i++)
printf("%ld ",arr[i]);
printf("\n");
}
return 0;
}
i executed this code on gcc compiler in ubuntu, it is working perfectly with all the constraints satisfied but when I uploaded this code on my teacher's portal which has a compiler and executed the code, it said Runtime error -
nzec which means a non-zero exception which is used to signify that main() does not have "return 0;" statement or exception thrown by c++ compiler.
Please, can anyone help me what is wrong in my code as there is a return 0; statement in my code. Please Help.
Everyone has pointed out multiple use of exits ... Can I reduce them using any other way in place of exit()?
My guess is that it has to do with the various exit(1) statements you have for error conditions.
As pointed out by Dave Costa, exit(1) could be the cause
Another possible problem is the size of the allocated array:
arr = (long int *)malloc(sizeof(int)*n);
should be:
arr = malloc(sizeof(long int)*n);
And note that you don't need to use pow for constants:
c1 = (long int)pow(10,5);
c2 = (long int)pow(10,9);
could be replaced with:
c1 = 1e5L;
c2 = 1e9L;

recursive function error: "stack overflow"

I wrote this function that supposed to find smallest positive integer that is divisible by every number 1 through 20. I get "stack overflow error", even though, when I test for numbers 1 through 10, it works just fine.
here is my code:
#include<iostream>
#include<cstdlib>
using namespace std;
// function prototype
int smallPos(int k, int m,int n);
int main(){
printf("the smallest positive number that is divisible by 1 through 20 is %d ", smallPos(1,1,13));
}
int smallPos(int k, int n, int m){
int div=0;
for(int i = n;i<=m;i++) {
if (k%i==0)
div++;
}
if (div==m) {
return k;
} else {
k+=1;
smallPos(k,n,m);
}
}
Why does it happen? The number shouldn't be that big anyway.
Thank you!
The final condition (div == m) will never be true. For div to become equal to m, the number k should be divisible by all of the numbers in range [n,m).
Edit: I've reread the text in the printf() call to understand what the function does. You're looking for the first number divisible by all numbers in the range. If my calculations are correct, this number should be the product of all unique prime factors of the numbers in the range. For the range [1,13] (as per the function call, not the text), this number should be:
30030 = 1 * 2 * 3 * 5 * 7 * 9 * 11 * 13
Now, this means you are going to invoke the function recursively over 30,000 times, which is obviously way too many times for the size of stack you're using (defaults are relatively small). For a range this size, you should really consider writing an iterative function instead.
Edit: here's an iterative version that seems to work.
int smallPos ( int n, int m )
{
int k = 0;
while ( ++k )
{
int count = 0;
for (int i = n; i<=m; i++)
{
if (k%i==0) {
++count;
}
}
if (count == (m-n+1)) {
return k;
}
}
return k;
}
Indeed, the result for smallPos(1,10), the result is 2520. It seems my previous estimate was a lower bound, not a fixed result.
Your smallPos function incurs undefined behaviour since it is not returning a value in all execution paths. You may want to say return smallPos(k,n,m); in the last part (or just return smallPos(k + 1, n, m); in one go).