"Write a program which reads n numbers and which determines a number c, the smallest of the read numbers which contains the largest digit found in them."
Example: n=10 ; numbers: 23 12 64 12 72 345 67 23 71 634 ; c=67 (the largest digit found in these numbers is 7 and it can be found in 72, 67, 71. The smallest number is 67)
I don't know why, but my program doesn't work. Every time, it shows me that c=0.
#include <iostream>
using namespace std;
int main()
{
int n, prec, crt, digitMax, t, a, i, c;
digitMax=0;
t=0;
cout<<"Give the number of numbers: "; cin>>n;
cout<<"Give the first number: "; cin>>prec;
do{
a=prec%10;
prec=(prec-a)/10;
if(a>digitMax){
digitMax=a;
}
} while(prec!=0);
for(i=1; i<n; i++){
cout<<"Give the next number: "; cin>>crt;
do{
a=crt%10;
crt=(crt-a)/10;
if(a>t){
t=a;
}
} while(crt!=0);
if(digitMax>t){
c=prec;
} else if(digitMax<t) {
digitMax=t;
c=crt;
} else if(prec>=crt){
c=crt;
} else{
c=prec;
}
prec=crt;
}
cout<<"c is "<<c;
}
Problem is that you are doing everything inside a single function make it very complex. The proper way to tackle problem is first define a small functions whcih are doing smaller tasks.
One which calculates biggest digit in number:
int BigestDigitOf(int x)
{
x = std::abs(x);
int biggestDigit = 0;
while (x)
{
biggestDigit = std::max(biggestDigit, x%10);
x/=10;
}
return biggestDigit;
}
And one which compares two numbers according to c definition:
bool BiggerDigitOrSmallerValue(int a, int b)
{
auto bdA = BigestDigitOf(a);
auto bdB = BigestDigitOf(b);
if (bdA > bdB) {
return true;
}
return bdA == bdB && a < b;
}
After that solving your problem is very simple (one line if STL is used).
Related
I am new to coding and just starting with the c++ language, here I am trying to find the number given as input if it is Armstrong or not.
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.
But even if I give not an armstrong number, it still prints that number is armstrong.
Below is my code.
#include <cmath>
#include <iostream>
using namespace std;
bool ifarmstrong(int n, int p) {
int sum = 0;
int num = n;
while(num>0){
num=num%10;
sum=sum+pow(num,p);
}
if(sum==n){
return true;
}else{
return false;
}
}
int main() {
int n;
cin >> n;
int i, p = 0;
for (i = 0; n > 0; i++) {
n = n / 10;
}
cout << i<<endl;
if (ifarmstrong(n, i)) {
cout << "Yes it is armstorng" << endl;
} else {
cout << "No it is not" << endl;
}
return 0;
}
A solution to my problem and explantation to what's wrong
This code
for (i = 0; n > 0; i++) {
n = n / 10;
}
will set n to zero after the loop has executed. But here
if (ifarmstrong(n, i)) {
you use n as if it still had the original value.
Additionally you have a error in your ifarmstrong function, this code
while(num>0){
num=num%10;
sum=sum+pow(num,p);
}
result in num being zero from the second iteration onwards. Presumably you meant to write this
while(num>0){
sum=sum+pow(num%10,p);
num=num/10;
}
Finally using pow on integers is unreliable. Because it's a floating point function and it (presumably) uses logarithms to do it's calculations, it may not return the exact integer result that you are expecting. It's better to use integers if you are doing exact integer calculations.
All these issues (and maybe more) will very quickly be discovered by using a debugger. much better than staring at code and scratching your head.
I was doing this program in which I am supossed to print gapful numbers all the way up to a specific value. The operations are correct, however, for some reason after printing a couple of values the program crashes, what can I do to fix this problem?
Here's my code:
#include<math.h>
#include<stdlib.h>
using namespace std;
void gapful(int);
bool gapCheck(int);
int main(){
int n;
cout<<"Enter a top number: ";
cin>>n;
gapful(n);
system("pause");
return 0;
}
void gapful(int og){
for(int i=0; i<=og; i++){
fflush(stdin);
if(gapCheck(i)){
cout<<i<<" ";
}
}
}
bool gapCheck(int n){
int digits=0;
int n_save,n1,n2,n3;
if(n<100){
return false;
}
else{
n_save=n;
while(n>10){
n/=10;
digits++;
}
digits++;
n=n_save;
n1=n/pow(10, digits);
n2=n%10;
n3=n1*10 + n2;
if(n%n3 == 0){
return true;
}
else{
return false;
}
}
}
I'm open to any suggestions and comments, thank you. :)
For n == 110, you compute digits == 3. Then n1 == 110 / 1000 == 0, n2 == 110 % 10 == 0, n3 == 0*10 + 0 == 0, and finally n%n3 exhibits undefined behavior by way of division by zero.
You would benefit from more functions. Breaking things down into minimal blocks of code which represent a single purpose makes debugging code much easier. You need to ask yourself, what is a gapful number. It is a number that is evenly divisible by its first and last digit. So, what do we need to solve this?
We need to know how many digits a number has.
We need to know the first digit and the last digit of the number.
So start out by creating a function to resolve those problems. Then, you would have an easier time figuring out the final solution.
#include<math.h>
#include <iostream>
using namespace std;
void gapful(int);
bool gapCheck(int);
int getDigits(int);
int digitAt(int,int);
int main(){
int n;
cout<<"Enter a top number: " << endl;
cin>>n;
gapful(n);
return 0;
}
void gapful(int og){
for(int i=1; i<=og; ++i){
if(gapCheck(i)){
cout<<i << '-' <<endl;
}
}
}
int getDigits(int number) {
int digitCount = 0;
while (number >= 10) {
++digitCount;
number /= 10;
}
return ++digitCount;
}
int digitAt(int number,int digit) {
int numOfDigits = getDigits(number);
int curDigit = 0;
if (digit >=1 && digit <= numOfDigits) { //Verify digit is in range
while (numOfDigits != digit) { //Count back to the digit requested
number /=10;
numOfDigits -=1;
}
curDigit = number%10; //Get the current digit to be returned.
} else {
throw "Digit requested is out of range!";
}
return curDigit;
}
bool gapCheck(int n){
int digitsN = getDigits(n);
if (digitsN < 3) { //Return false if less than 3 digits. Single digits do not apply and doubles result in themselves.
return false;
}
int first = digitAt(n,1) * 10; //Get the first number in the 10s place
int second = digitAt(n,digitsN); //Get the second number
int total = first + second; //Add them
return n % total == 0; //Return whether it evenly divides
}
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
Here is my assignment:
A prime number is a number greater than 1 which is only evenly divisible by 1 and itself. For this assignment you will find which numbers from 2 to n (where n is a user-specified number) are prime.
Ask the user for a number, n, greater than 2. Keep asking for a number until a number greater than 2 is provided. Assume that the user will only enter numbers (that is, you do not need to check if a user enters text).
Use a loop to iterate on a variable, i, from 2 through n. For each iteration, check all numbers from 2 through i to determine whether the number is prime. If it is prime, print out i and the word "Prime".
Use the modulus operator, %, to determine if a number is prime
Here is what I have so far. It doesnt work. And I dont know why. please help, im a business student taking basic programming as an elective.
#include <iostream>
using namespace std;
int main()
{
int n;
int i;
int x;
while (n<=2)
{
cout << "Enter a number greater then 2: \n";
cin >> n;
for (x=n; x>=2; x--)
{
bool prime = false;
for (i=2; i<x; i++)
{
if (x%i==0)
{
prime = true;
}
}
if (prime==false)
{
cout << x << " Prime.\n";
}
}
}
return 0;
}
I didn't actually used your code because of indentication it was little bit of hard to read. But I wrote a new method for you. I suggest always divide your code into methods to make it more managable. You can call this in your main method
bool checkPrime(int number)
{ // input: num an integer > 1
// Returns: true if num is prime
// false otherwise.
int i;
for (i=2; i<number; i++)
{
if (number % i == 0)
{
return false;
}
}
return true;
}
And here is how can you call this method in the main:
int main()
{
int number;
cout << "Enter an integer (>1): ";
cin >> number;
if (checkPrime(number))
{
cout << number << " is prime." << endl;
}
else
{
cout << number << " is not prime." << endl;
}
// I think this is more convention than anything.
return 0;
}
It may not be the optimal program out there, but this should work:
#include <iostream>
using namespace std;
int main()
{
int n;
int i;
int x;
cout << "Enter a number greater then 2: \n";
cin >> n;
while (n<=2)
{
cout << "Enter a number greater then 2: \n";
cin >> n;
}
for (x=n; x>=2; --x)
{
for (i=2; i<x; ++i)
{
bool prime = true;
for (j=2; j<i/2; ++j)
{
if (i%j==0)
{
prime = false;
break;
}
}
if (prime)
{
cout << j << " Prime.\n";
}
}
}
return 0;
}
There are two easy means to go faster: first there is no need to test potential divisors that are too big (as pointed out by arne), and second, there is no need to test even numbers except 2.
Something like this:
#include <cassert>
bool is_prime(unsigned n)
{
if (n == 2)
return true;
if (n <= 1
|| n % 2 == 0)
return false;
for (int d = 3; d * d < n; ++d)
if (n % d == 0)
return false;
return true;
}
int main()
{
assert(!is_prime(0));
assert(!is_prime(1));
assert(is_prime(2));
assert(is_prime(3));
assert(!is_prime(4));
assert(is_prime(5));
assert(!is_prime(6));
assert(!is_prime(256));
assert(is_prime(257));
}
Of course, even faster is building a table of primes, and using this table as potential divisors, instead of every odd number. Makes sense if you have several numbers to check.
Please, say, why it let say you it does not work? Among others I get this output.
Enter a number greater then 2:
100
97 Prime.
89 Prime.
83 Prime.
79 Prime.
73 Prime.
71 Prime.
67 Prime.
61 Prime.
59 Prime.
53 Prime.
47 Prime.
43 Prime.
41 Prime.
37 Prime.
31 Prime.
29 Prime.
23 Prime.
19 Prime.
17 Prime.
13 Prime.
11 Prime.
7 Prime.
5 Prime.
3 Prime.
2 Prime.
But as int n; leaves n uninitialized, the while loop might not be entered.
I think the Answer 1 function checkprime(int number) can improved but purely on preformance basis, consider the fact that prime numbers cannot be even.So if add an extra check to see if (number % 2 == 0) will reduce a lot of iteration of the for loop, and for the remaining i think iterating the loop from 2 to 9 is enough rather than 2 to n. Too many iterations will slow you down on larger numbers.
I am wondering I can get some help at debugging or spotting the error in my program. The objective is to obtain user input and then display primes from input to zero, greatest prime to lowest.
Problem is the output includes the user input which may or may not be a prime number in itself, and repeats primes several times :(
Also, I am wondering why 2 isn't included?
My code:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int prime, division, input;
cout << "Please enter a number you wish to count down prime numbers from." << endl;
cin >> input;
for (prime = input ; prime >=2 ; prime-- )
{
for (division = 2 ; division < prime ; division++ )
{
if (prime % division == 0)
{
break;
}
else
{
cout << prime << " ";
}
}
}
return 0;
}
My output:
Please enter a number you wish to count down prime numbers from.
15
15 13 13 13 13 13 13 13 13 13 13 13 11 11 11 11 11 11 11 11 11 9 7 7 7 7 7 5 5 5 3
Thanks for those who help!
This is a program which tells whether the input number is prime or not.Any number is completely divisible by a number which is always less than it.
In case of prime numbers they are completely divisible by 1 and itself;
So i have used a counter variable which counts how many times a number is completely divisible by a number or numbers less than it.
The count will be always 2 for prime numbers and count will be more than two for others.
Count will be 1 for one...
So the program is as follows....
#include<iostream.h>
#include<conio.h>
class prime
{
int a;
public:
void check();
};
void prime::check()
{
cout<<"Insert a number";
cin>>a;
int count=0;
for(int i=a;i>=1;i--)
{
if(a%i==0)
{
count++;
}
}
if(count==1)
{
cout<<"\nOne is neither prime nor composite";
}
if(count>2)
{
cout<<"\nthe number is not prime its composite" ;
}
if(count==2)
{
cout<<"\nthe numner is prime";
}
}
void main()
{
clrscr();
prime k;
k.check();
getch();
}
To print all the prime numbers less than the number given as input; code is as follows:
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
class prime
{
int a;
int i;
public:
void display();
};
void prime::display()
{
cout<<"Enter any number to find primes less than it";
cin>>a;
int count=0;
for(int j=a;j>=1;j--)
{
for(int i=1;i<=j;i++)
{
if(j%i==0)
{
count++;
}
}
if(count==2)
{
cout<<"\n"<<j;
}
count=0;
}
}
void main()
{
clrscr();
prime k;
k.display();
getch();
}
Try this code
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int prime, division, input;
cout << "Please enter a number you wish to count down prime numbers from." << endl;
cin >> input;
for (prime = input ; prime >=2 ; prime--)
{
boolean isDivisible = false;
for (division = 2 ; division < prime ; division ++)
{
if (prime % division == 0)
{
isDivisible = true;
}
}
if (isDivisible == false)
{
cout << prime << " ";
}
}
return 0;
}
For the first problem:
for 9, when division == 2, 9 % 2 ==1, so 9 is printed.Rather than You should have a flag value to denote if a number is prime or not, and print the number after you are sure it is prime.
For 2, EDIT: when prime == 2, and because division < prime is the condition that the inner loop get executed, the inner loop exits without running. All credits go to Marlon!
Check your inner for loop. Each run through the loop, your initializer gets reset to 2. Then you do Mod 2 on the suspected prime. If you get 0, all you really know is that the number is even. That might lead you to quickly say that the number isn't prime, but 2 mod 2 is 0, and 2 is prime. After the loop, "division" becomes 3. 15 mod 3 is 0. At that point, you break out of the loop, but 15 is NOT prime. Check your algorithm for determining primes. You could have it check against known primes, but that's not dynamic enough. There are other methods, one of which revolves around determining the suspected prime number's square root. Finally, you could do some good old (long) paper-pencil debugging.
Your inner loop is not correct. Its not printing primes, just odd numbers. It checks whether a number is divisible by 2 during first iteration and an even number will always be divisble. So the inner loop always breaks out if the number is even but it prints the number if odd and continues doing so till the loop breaks or terminates.
Lets try to get this with an example, the outer loop is at 9. The inner loop will check if its divisble by 2, since its not it'll print out the number and continue again. Next iteration will check whether its divisible by 3, since it is it'll break out.
And try using a function to check whether a number is prime that makes it more modular. Here's a little optimized version...
bool prime(int num)
{
int root = sqrt(num);
if(num == 2)
return true;
if(num%2 == 0)
return false;
for(int i=3;i<=root+1;i=i+2)
if(num % i == 0)
return false;
return true;
}