Can u give me some help?I'm beginner and I dont know what's wrong with my program.It generates me all numbers to n not just prime numbers. why?
#include <iostream>
using namespace std;
int main()
{
unsigned int i,n,d;
bool prim;
cout<<"n=";
cin>>n;
for(i=2;i<=n;i=i+1)
{
prim=true;
for(d=2;d<=i/2;d=d+1)
if(i%d==0)
{
prim=false;
break;
}
(prim);
cout<<i<<",";
}
return 0;
}
Because (prim) is not the same as:
if (prim) {
cout << i << ",";
}
On a side note:
d=d+1 and i=i+1 can just be d++ and i++
You can declare variables inside the loops like: for (int i = 0;
Instead of (prim); use if(prim). The rest of your code is correct.
#include <iostream>
using namespace std;
int main()
{
unsigned int i,n,d;
bool prim;
cout<<"n=";
cin>>n;
for(i=2;i<=n;i=i+1)
{
prim=true;
for(d=2;d<=i/2;d=d+1)
if(i%d==0)
{
prim=false;
break;
}
if(prim)
cout<<i<<", ";
}
return 0;
}
Your condition for printing is not correct.
(prim);cout<<i<<",";
should be
if(prim) cout<<i<<",";
Note that your logic prints primes <= n, not the first n prime numbers.
You missed off the if:
if (prim) cout << i << ',';
The if statement could be reduced a little bit:
prim && cout<<i<<",";
This is because of the shortcut evaluation of logical expressions. So cout will only be evaluated if prime is true. If it is false, cout will be not evaluated as the expression is false anyway.
Minor comment: The divisor (d) may be increased till floor(sqr(i)), not till i/2 (more effective). Variable i may be started from 3 and increased by 2 as all even numbers are not prime (except 2, it can be printed without counting...).
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 am new to c++ and I have been tasked to write a code which finds the smallest prime factor of a number using recursion. If N is less than 2 the code should return 1. If N is a prime number itself the code should return N. Otherwise the code should return the smallest prime factor of N. I have attempted the question but I have used a for loop to check for the lowest prime factor and I am unsure if this method in the context of my answer is iterative or recursive. To call the function for main the user should enter lowestPrimeFactor(x);, where x is the number they want to find the lowest prime factor for. I am stuck with trying to change the iterative section to recursive, where the code checks for the lowest prime factor. I would appreciate any feedback.
#include <stdio.h>
#include <iostream>
#include <math.h>
long lowestPrimeFactor(long N, long i=2) {
if(N<2){ //if N is less than 2, return 1
std::cout << 1; //print to screen to check
return 1;
}
bool isPrime =true; //Check if number is prime
for(i=2;i<=N/2; ++i){
if(N%i==0){
isPrime=false;
break;
}
}
if (isPrime){
std::cout<<N;
return N;
}
for (int i = 3; i* i <= N; i+=2){ //This is where I am unsure how to translate to recursive as it is based of an iterative solution
if(N%i == 0)
std::cout<<i;
return i;
}
//Driver code to check functionality
int main(){
lowestPrimeFactor(19);
}
EDIT
I think I have modified the code correctly to be recursive for the prime factor check
//Recursive
if(i*i<=N){
N%i==0; lowestPrimeFactor(i);
}
else return i;
Just need to try and adjust the bool part to be recursive too
Try this:
#include <iostream>
using namespace std;
long lowestPrimeFactor(long N, long i = 2) {
if (N % i == 0) // Test for factor
return i;
else if (i < N * N)
return lowestPrimeFactor(N, i + 1); // Test next factor
else
return N;
}
void test(long N){
// Format results
cout << N << " gives " << lowestPrimeFactor(N) << endl;
}
int main() {
for (long N = 2; N < 30; ++N) // Generate some test cases
test(N);
}
This has the inefficiency that it tests for non-prime factors too (which I think the original solution also does) so really rather than recursing with i + 1 (the next integer after i) we should be calculating and passing in the next prime after i.
The required code, if you want to use recursion for checking out the lowest prime factor instead of the last for loop would be as follows:
#include <iostream>
long lowestPrimeFactor(long N,long pr = 3)
{
bool isPrime =true;
if(N<2)
{ //if N is less than 2, return 1
std::cout << N << std::endl;//print to screen to check
return 1;
}
else
{
for(long i=2;i<=N/2; ++i)
{
if(N%i==0)
{
isPrime=false;
break;
}
}
}
if(isPrime)
{
std::cout << N << std::endl;
return N;
}
else
{
if(N%2==0){
std::cout << 2 << std::endl;
return 2;
}
else
{
if(N%pr == 0)
{
std::cout << pr << std::endl;
return pr;
}
else
{
return lowestPrimeFactor(N,pr+2);
}
}
}
}
//Driver code to check functionality
int main()
{
lowestPrimeFactor(19);
lowestPrimeFactor(20);
lowestPrimeFactor(7);
lowestPrimeFactor(1);
lowestPrimeFactor(15);
}
This isn't fully recursive but it checks for only prime numbers till 7 after which it checks for 9 and so on i.e odd numbers which even the original code had.
Note: Prime factors it checks properly: 2,3,5,7 and prime numbers
I wrote a C++ program that prints all prime numbers lower than n, but the program keeps crashing while executing.
#include <iostream>
using namespace std;
bool premier(int x) {
int i = 2;
while (i < x) {
if (x % i == 0)
return false;
i++;
}
return true;
}
int main() {
int n;
int i = 0;
cout << "entrer un entier n : ";
cin >> n;
while (i < n) {
if (n % i == 0 && premier(i))
cout << i;
i++;
}
;
}
As Igor pointed out, i is zero the first time when n%i is done. Since you want only prime numbers and the smallest prime number is 2, I suggest you initialise i to 2 instead of 0.
You want to print all prime numbers less than n and has a function to check primality already.
Just
while (i < n){
if ( premier(i) == true )
cout<<i;
i++;
}
And while printing, add a some character to separate the numbers inorder to be able to distinguish them like
cout<<i<<endl;
P.S: I think you call this a C++ program. Not a script.
Edit: This might interest you.
#include <iostream>
#include <cmath>
using std::cin;
using std::cout;
using std::endl;
int prime(int n)
{
int i;
if (n == 1) return 0; // zero- not prime
if (n == 2) return 1; // one- prime
for (i = 2; i <= ceil(sqrt(n)); i++) {
if (n % i == 0) return 0; // remainder is zero
}
return 1;
}
int main()
{
unsigned long n;
while (cin >> n) {
cout << prime(n) << endl;
}
}
I know that 0 means not prime and 1 means prime. Can someone please explain how are all the return functions used to accomplish this?
Why not use cout << "0" for not prime and cout << "1" for prime?
Yes, you could cout directly from the function. That would be valid.
But when you make a mathematical function, it's more conventional to return its value, so that the code that called it can then do whatever it likes. It can cout it, or save it to a variable, or perform other calculations.
If the function directly couted the result, then you're stuck: it can only do that one thing with the result. That's limiting, and for no benefit.
I am writing a program to find the factorial of a user inputted number. My program works from, except for finding the factorial of 0. The requirement is that the factorial of 0 should output one, but I cannot think of a way to write this capability into the code without creating a special case for when 0 is entered. This is what I have so far
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int startingNumber = 0;
double factorialize = NULL;
while(startingNumber != -1) {
cout << "Enter the numbr to factorial: ";
cin >> startingNumber;
factorialize = startingNumber;
for(int x=startingNumber-1;x>=1;x--) {
factorialize = factorialize*x;
}
cout << factorialize << endl;
factorialize = NULL;
}
return 0;
}
This outputs a factorial accurately for all cases except 0. Is there a way to do this that doesn't require a special case? I am thinking no because when I read about the reasons for why 0! is 1, it says that it is defined that way, in other words, you cannot reason your way into why it is 1. Just like x^0, 0! = 1 has a different logic as to why than why 2^2 is 4 or 2! = 2.
try this:
factorialize = 1;
for(int x=2; x<=startingNumber;x++)
factorialize *= x;
Try this:
for (unsigned int n; std::cin >> n; )
{
unsigned int result = 1;
for (unsigned int i = 1; i <= n; ++i) { result *= i; }
std::cout << n << "! = " << result << "\n";
}
You can change the result type a bit (unsigned long long int or double or long double), but ultimately you won't be able to compute a large number of factorials in hardware.
First of all I do not see how it can be calculated accurately, as you multiply startingNumber twice. So just fix the logic with:
factorialize = 1.0;
for(int x=startingNumber;x>=1;x--) {
factorialize = factorialize*x;
}
And it should calculate factorial properly as well as handling 0 the proper way.
Also you should not use NULL as initial value for double, it is for pointers.
There is a complete factorial of number program of C++ which includes the facility of factorial of positive number,negative and zero.
#include<iostream>
using namespace std;
int main()
{
int number,factorial=1;
cout<<"Enter Number to find its Factorial: ";
cin>>number;
if(number<0
)
{
cout<<"Not Defined.";
}
else if (number==0)
{
cout<<"The Facorial of 0 is 1.";
}
else
{
for(int i=1;i<=number;i++)
{
factorial=factorial*i;
}
cout<<"The Facorial of "<<number<<" is "<<factorial<<endl;
}
return 0;
}
You can read full program logic on http://www.cppbeginner.com/numbers/how-to-find-factorial-of-number-in-cpp/
The function listed below returns the factorial FASTER than any solution posted here to this date:
const unsigned int factorial(const unsigned int n)
{
unsigned int const f[13] = { 1,1,2,6,24,120,720,5040,40320,362880,3628800,39916800,479001600 };
return f[n];
}
I looks silly but it works for all factorials that fit into a 32-bit unsigned integer.